List of usage examples for org.apache.commons.cli ParseException printStackTrace
public void printStackTrace()
From source file:pt.ua.tm.neji.train.cli.TrainMain.java
public static void main(String[] args) { CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information."); options.addOption("c", "sentences-input", true, "File with corpus sentences."); options.addOption("a", "annotations-input", true, "File with corpus annotations."); options.addOption("if", "input-format", true, "BC2, A1, JNLPBA or SERIALIZED."); options.addOption("f", "features", true, "Features."); options.addOption("o", "model output path", true, "Path to save the model."); options.addOption("m", "model name", true, "Name of the model."); options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries."); options.addOption("t", "threads", true, "Number of threads. By default, is 1."); options.addOption("s", "serialize", true, "File to save the serialized corpus."); CommandLine commandLine = null;/* w w w. jav a 2s . c o m*/ try { // Parse the program arguments commandLine = parser.parse(options, args); } catch (ParseException ex) { logger.error("There was a problem processing the input arguments.", ex); return; } // Show help text if (commandLine.hasOption('h')) { printHelp(options, ""); return; } // No options if (commandLine.getOptions().length == 0) { printHelp(options, ""); return; } String fileSentencesIn = null; InputFormat inputFormat; String fileAnnotationsIn = null; // Get Input format if (commandLine.hasOption("if")) { inputFormat = InputFormat.valueOf(commandLine.getOptionValue("if")); } else { printHelp(options, "Please specify the input format."); return; } // Get sentences file or folder for input if (commandLine.hasOption('c')) { fileSentencesIn = commandLine.getOptionValue('c'); File test = new File(fileSentencesIn); if (inputFormat.equals(InputFormat.BC2) || inputFormat.equals(InputFormat.SERIALIZED) || inputFormat.equals(InputFormat.JNLPBA)) { // File formats or SERIALIZED format if (!test.isFile() || !test.canRead()) { logger.error("The specified path is not a file or is not readable."); return; } } else { // Folder formats if (!test.isDirectory() || !test.canRead()) { logger.error("The specified path is not a folder or is not readable."); return; } // Verify if corpus is not empty A1Pairs aiPairs = A1Utils.separateTextAnnotations(test.listFiles()); if (aiPairs.getAnnotations().length == 0) { String m = "The provided sentences directory does not " + "contain annotations files."; logger.error(m); return; } } fileSentencesIn = test.getAbsolutePath(); fileSentencesIn += File.separator; } else { printHelp(options, "Please specify the senteces file or folder."); return; } // Get annotations file for input if (inputFormat.equals(InputFormat.BC2) && commandLine.hasOption('a')) { fileAnnotationsIn = commandLine.getOptionValue('a'); File test = new File(fileAnnotationsIn); if (test.isDirectory() || !test.canRead()) { logger.error("The specified path is not a file or is not readable."); return; } fileAnnotationsIn = test.getAbsolutePath(); fileAnnotationsIn += File.separator; } // Get model output path (path where model should be saved) String modelOutputPath; if (commandLine.hasOption("o")) { modelOutputPath = commandLine.getOptionValue('o'); File test = new File(modelOutputPath); if (test.isFile() || !test.canRead()) { logger.error("The specified path is not a folder or is not readable."); return; } modelOutputPath = test.getAbsolutePath(); modelOutputPath += File.separator; } else { printHelp(options, "Please specify the model output path."); return; } // Get model name (name for the model) String modelName; if (commandLine.hasOption('m')) { modelName = commandLine.getOptionValue('m'); } else { printHelp(options, "Please specify the model name."); return; } if (modelName.contains(".gz")) modelName = modelName.substring(0, modelName.lastIndexOf(".gz")); String modelFolderPath = modelOutputPath + modelName + File.separator; // Get features String featuresFilePath; if (commandLine.hasOption('f')) { featuresFilePath = commandLine.getOptionValue('f'); File test = new File(featuresFilePath); if (test.isDirectory() || !test.canRead()) { logger.error("The specified features file path is not a file or is not readable."); return; } featuresFilePath = test.getAbsolutePath(); featuresFilePath += File.separator; } else { printHelp(options, "Please specify the model configuration file."); return; } // Read features file (contains parsing and entity) logger.info("Loading config..."); ModelConfig config = new ModelConfig(featuresFilePath); // Get dictionaries folder String dictionariesFolder = null; if (commandLine.hasOption('d')) { dictionariesFolder = commandLine.getOptionValue('d'); File test = new File(dictionariesFolder); if (!test.isDirectory() || !test.canRead()) { logger.error("The specified dictionaries path is not a folder or is not readable."); return; } dictionariesFolder = test.getAbsolutePath(); dictionariesFolder += File.separator; } // Get threads int numThreads = 1; if (commandLine.hasOption('t')) { String threadsText = commandLine.getOptionValue('t'); numThreads = Integer.parseInt(threadsText); if (numThreads <= 0 || numThreads > 32) { logger.error("Illegal number of threads. Must be between 1 and 32."); return; } } // Get serialization info (file to save the serialized corpus) String serializedFilePath = null; if (commandLine.hasOption('s')) { serializedFilePath = commandLine.getOptionValue('s'); File test = (new File(serializedFilePath)).getParentFile(); if (test != null) { if (test.isFile() || !test.canRead()) { logger.error("The specified serialize file path is not a folder or is not readable."); return; } serializedFilePath = test.getAbsolutePath() + File.separator + (new File(serializedFilePath)).getName(); } if (!serializedFilePath.endsWith(".gz")) serializedFilePath += ".gz"; } // Parsing variables ParserTool parsingTool = ParserTool.GDEP; ParserLanguage parsingLanguage = ParserLanguage.ENGLISH; ParserLevel parsingLevel; // Get parsing if (config.isNLP()) parsingLevel = ParserLevel.DEPENDENCY; else if (config.isChunk()) parsingLevel = ParserLevel.CHUNKING; else if (config.isPos()) parsingLevel = ParserLevel.POS; else if (config.isLemma()) parsingLevel = ParserLevel.LEMMATIZATION; else parsingLevel = ParserLevel.TOKENIZATION; if (!inputFormat.equals(InputFormat.SERIALIZED)) { // -- Phase 1 (First pipeline) -- // Set output formats List<OutputFormat> outputFormats = new ArrayList<>(); outputFormats.add(OutputFormat.GZCORPUS); // Define context configuration ContextConfiguration descriptor = null; try { descriptor = new ContextConfiguration.Builder().withInputFormat(inputFormat) .withOutputFormats(outputFormats).withParserTool(parsingTool) .withParserLanguage(parsingLanguage).withParserLevel(parsingLevel).trainBuildPhase1(); } catch (NejiException ex) { ex.printStackTrace(); System.exit(1); } // Create context TrainContext context = new TrainContext(descriptor, config, dictionariesFolder, modelFolderPath, null, 1); try { BatchExecutor batchExecutor = new TrainBatchExecutor(fileSentencesIn, fileAnnotationsIn, numThreads); batchExecutor.run(TrainProcessor.class, context); } catch (Exception ex) { logger.error("There was a problem running the batch.", ex); } // -- Phase 2 (Merge corpus) -- if (inputFormat.equals(InputFormat.A1)) { // Folder formats logger.info("Merging corpus..."); try { Utils.mergeGZCorpus(modelFolderPath, modelFolderPath + File.separator + modelName + ".gz"); } catch (NejiException ex) { System.out.println("Error: An error ocurred while merging the corpus. " + ex.getMessage()); } } } // -- Phase 3 (Second pipeline) -- // Set serialized corpus path String corpusLocationPath = null; if (inputFormat.equals(InputFormat.A1)) { // Folder formats corpusLocationPath = modelFolderPath + File.separator + modelName + ".gz"; } else if (inputFormat.equals(InputFormat.BC2) || inputFormat.equals(InputFormat.JNLPBA)) { // File formats corpusLocationPath = modelFolderPath + File.separator + FilenameUtils.getBaseName((new File(fileSentencesIn)).getName()) + ".gz"; } else { // Serialized format corpusLocationPath = fileSentencesIn; } // Save serialized corpus if (serializedFilePath != null) { logger.info("Saving serialized corpus..."); File gzCorpusFile = new File(corpusLocationPath); File serializeFile = new File(serializedFilePath); try { Files.copy(gzCorpusFile, serializeFile); } catch (IOException ex) { System.out.println("Error: There was a problem saving the serialized corpus. " + ex.getMessage()); } } // Set output formats List<OutputFormat> outputFormats = new ArrayList<>(); outputFormats.add(OutputFormat.MODEL); // Define context configuration ContextConfiguration descriptor = null; try { descriptor = new ContextConfiguration.Builder().withInputFormat(InputFormat.SERIALIZED) .withOutputFormats(outputFormats).trainBuildPhase2(); } catch (NejiException ex) { ex.printStackTrace(); System.exit(1); } // Create context TrainContext context = new TrainContext(descriptor, config, dictionariesFolder, corpusLocationPath, modelFolderPath, 2); try { BatchExecutor batchExecutor = new TrainBatchExecutor(); batchExecutor.run(TrainProcessor.class, context); } catch (Exception ex) { logger.error("There was a problem running the batch.", ex); } // Delete corpus file if (!inputFormat.equals(InputFormat.SERIALIZED)) { (new File(corpusLocationPath)).delete(); } // Delete tmp file (if it exists) (new File("tmp.txt")).delete(); }
From source file:pt.ua.tm.neji.web.cli.WebMain.java
public static void main(String[] args) { // Set JSP to use Standard JavaC always System.setProperty("org.apache.jasper.compiler.disablejsr199", "false"); CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information."); options.addOption("v", "verbose", false, "Verbose mode."); options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries."); options.addOption("m", "models", true, "Folder that contains the ML models."); options.addOption("port", "port", true, "Server port."); options.addOption("c", "configuration", true, "Configuration properties file."); options.addOption("t", "threads", true, "Number of threads. By default, if more than one core is available, it is the number of cores minus 1."); CommandLine commandLine;/*from w w w . j ava 2 s . c o m*/ try { // Parse the program arguments commandLine = parser.parse(options, args); } catch (ParseException ex) { logger.error("There was a problem processing the input arguments.", ex); return; } // Show help text if (commandLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(150, "./nejiWeb.sh " + USAGE, HEADER, options, FOOTER); return; } // Get threads int numThreads = Runtime.getRuntime().availableProcessors() - 1; numThreads = numThreads > 0 ? numThreads : 1; if (commandLine.hasOption('t')) { String threadsText = commandLine.getOptionValue('t'); numThreads = Integer.parseInt(threadsText); if (numThreads <= 0 || numThreads > 32) { logger.error("Illegal number of threads. Must be between 1 and 32."); return; } } // Get port int port = 8010; if (commandLine.hasOption("port")) { String portString = commandLine.getOptionValue("port"); port = Integer.parseInt(portString); } // Get configuration String configurationFile = null; Properties configurationProperties = null; if (commandLine.hasOption("configuration")) { configurationFile = commandLine.getOptionValue("configuration"); try { configurationProperties = new Properties(); configurationProperties.load(new FileInputStream(configurationFile)); } catch (IOException e) { configurationProperties = null; } } if (configurationProperties != null && !configurationProperties.isEmpty()) { ServerConfiguration.initialize(configurationProperties); } else { ServerConfiguration.initialize(); } // Set system proxy if (!ServerConfiguration.getInstance().getProxyURL().isEmpty() && !ServerConfiguration.getInstance().getProxyPort().isEmpty()) { System.setProperty("https.proxyHost", ServerConfiguration.getInstance().getProxyURL()); System.setProperty("https.proxyPort", ServerConfiguration.getInstance().getProxyPort()); System.setProperty("http.proxyHost", ServerConfiguration.getInstance().getProxyURL()); System.setProperty("http.proxyPort", ServerConfiguration.getInstance().getProxyPort()); if (!ServerConfiguration.getInstance().getProxyUsername().isEmpty()) { final String proxyUser = ServerConfiguration.getInstance().getProxyUsername(); final String proxyPassword = ServerConfiguration.getInstance().getProxyPassword(); System.setProperty("https.proxyUser", proxyUser); System.setProperty("https.proxyPassword", proxyPassword); System.setProperty("http.proxyUser", proxyUser); System.setProperty("http.proxyPassword", proxyPassword); Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } } // Get verbose mode boolean verbose = commandLine.hasOption('v'); Constants.verbose = verbose; if (Constants.verbose) { MalletLogger.getGlobal().setLevel(Level.INFO); // Redirect sout LoggingOutputStream los = new LoggingOutputStream(LoggerFactory.getLogger("stdout"), false); System.setOut(new PrintStream(los, true)); // Redirect serr los = new LoggingOutputStream(LoggerFactory.getLogger("sterr"), true); System.setErr(new PrintStream(los, true)); } else { MalletLogger.getGlobal().setLevel(Level.OFF); } // Get dictionaries folder String dictionariesFolder = null; if (commandLine.hasOption('d')) { dictionariesFolder = commandLine.getOptionValue('d'); File test = new File(dictionariesFolder); if (!test.isDirectory() || !test.canRead()) { logger.error("The specified dictionaries path is not a folder or is not readable."); return; } dictionariesFolder = test.getAbsolutePath(); dictionariesFolder += File.separator; } // Get models folder String modelsFolder = null; if (commandLine.hasOption('m')) { modelsFolder = commandLine.getOptionValue('m'); File test = new File(modelsFolder); if (!test.isDirectory() || !test.canRead()) { logger.error("The specified models path is not a folder or is not readable."); return; } modelsFolder = test.getAbsolutePath(); modelsFolder += File.separator; } // Redirect JUL to SLF4 SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); // Output formats (All) List<OutputFormat> outputFormats = new ArrayList<>(); outputFormats.add(OutputFormat.A1); outputFormats.add(OutputFormat.B64); outputFormats.add(OutputFormat.BC2); outputFormats.add(OutputFormat.BIOC); outputFormats.add(OutputFormat.CONLL); outputFormats.add(OutputFormat.JSON); outputFormats.add(OutputFormat.NEJI); outputFormats.add(OutputFormat.PIPE); outputFormats.add(OutputFormat.PIPEXT); outputFormats.add(OutputFormat.XML); // Context is built through a descriptor first, so that the pipeline can be validated before any processing ContextConfiguration descriptor = null; try { descriptor = new ContextConfiguration.Builder().withInputFormat(InputFormat.RAW) // HARDCODED .withOutputFormats(outputFormats).withParserTool(ParserTool.GDEP) .withParserLanguage(ParserLanguage.ENGLISH).withParserLevel(ParserLevel.CHUNKING).build(); } catch (NejiException ex) { ex.printStackTrace(); System.exit(1); } // Create resources dirs if they don't exist try { File dictionariesDir = new File(DICTIONARIES_PATH); File modelsDir = new File(MODELS_PATH); if (!dictionariesDir.exists()) { dictionariesDir.mkdirs(); (new File(dictionariesDir, "_priority")).createNewFile(); } if (!modelsDir.exists()) { modelsDir.mkdirs(); (new File(modelsDir, "_priority")).createNewFile(); } } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } // Contenxt Context context = new Context(descriptor, MODELS_PATH, DICTIONARIES_PATH); // Start server try { Server server = Server.getInstance(); server.initialize(context, port, numThreads); server.start(); logger.info("Server started at localhost:{}", port); logger.info("Press Cmd-C / Ctrl+C to shutdown the server..."); server.join(); } catch (Exception ex) { ex.printStackTrace(); logger.info("Shutting down the server..."); } }
From source file:puma.central.pdp.CentralPUMAPDP.java
public static void main(String[] args) { // initialize log4j BasicConfigurator.configure();/*from ww w. j a v a2 s . com*/ CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("ph", "policy-home", true, "The folder where to find the policy file given with the given policy id. " + "For default operation, this folder should contain the central PUMA policy (called " + CENTRAL_PUMA_POLICY_FILENAME + ")"); options.addOption("pid", "policy-id", true, "The id of the policy to be evaluated on decision requests. Default value: " + GLOBAL_PUMA_POLICY_ID + ")"); options.addOption("s", "log-disabled", true, "Verbose mode (true/false)"); String policyHome = ""; String policyId = ""; // read command line try { CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Simple PDP Test", options); return; } if (line.hasOption("policy-home")) { policyHome = line.getOptionValue("policy-home"); } else { logger.log(Level.WARNING, "Incorrect arguments given."); return; } if (line.hasOption("log-disabled") && Boolean.parseBoolean(line.getOptionValue("log-disabled"))) { logger.log(Level.INFO, "Now switching to silent mode"); LogManager.getLogManager().getLogger("").setLevel(Level.WARNING); //LogManager.getLogManager().reset(); } if (line.hasOption("policy-id")) { policyId = line.getOptionValue("policy-id"); } else { logger.log(Level.INFO, "Using default policy id: " + GLOBAL_PUMA_POLICY_ID); policyId = GLOBAL_PUMA_POLICY_ID; } } catch (ParseException e) { logger.log(Level.WARNING, "Incorrect arguments given.", e); return; } // // STARTUP THE RMI SERVER // // if (System.getSecurityManager() == null) { // System.setSecurityManager(new SecurityManager()); // } final CentralPUMAPDP pdp; try { pdp = new CentralPUMAPDP(policyHome, policyId); } catch (IOException e) { logger.log(Level.SEVERE, "FAILED to set up the CentralPUMAPDP. Quitting.", e); return; } try { Registry registry; try { registry = LocateRegistry.createRegistry(RMI_REGISITRY_PORT); logger.info("Created new RMI registry"); } catch (RemoteException e) { // MDC: I hope this means the registry already existed. registry = LocateRegistry.getRegistry(RMI_REGISITRY_PORT); logger.info("Reusing existing RMI registry"); } CentralPUMAPDPRemote stub = (CentralPUMAPDPRemote) UnicastRemoteObject.exportObject(pdp, 0); registry.bind(CENTRAL_PUMA_PDP_RMI_NAME, stub); logger.info( "Central PUMA PDP up and running (available using RMI with name \"central-puma-pdp\" on RMI registry port " + RMI_REGISITRY_PORT + ")"); Thread.sleep(100); // MDC: vroeger eindigde de Thread om n of andere reden, dit lijkt te werken... } catch (Exception e) { logger.log(Level.SEVERE, "FAILED to set up PDP as RMI server", e); } // // STARTUP THE THRIFT PEP SERVER // //logger.log(Level.INFO, "Not setting up the Thrift server"); // set up server // PEPServer handler = new PEPServer(new CentralPUMAPEP(pdp)); // RemotePEPService.Processor<PEPServer> processor = new RemotePEPService.Processor<PEPServer>(handler); // TServerTransport serverTransport; // try { // serverTransport = new TServerSocket(THRIFT_PEP_PORT); // } catch (TTransportException e) { // e.printStackTrace(); // return; // } // TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor)); // System.out.println("Setting up the Thrift PEP server on port " + THRIFT_PEP_PORT); // server.serve(); // // STARTUP THE THRIFT PEP SERVER // //logger.log(Level.INFO, "Not setting up the Thrift server"); // set up server // do this in another thread not to block the main thread new Thread(new Runnable() { @Override public void run() { RemotePDPService.Processor<CentralPUMAPDP> pdpProcessor = new RemotePDPService.Processor<CentralPUMAPDP>( pdp); TServerTransport pdpServerTransport; try { pdpServerTransport = new TServerSocket(THRIFT_PDP_PORT); } catch (TTransportException e) { e.printStackTrace(); return; } TServer pdpServer = new TThreadPoolServer( new TThreadPoolServer.Args(pdpServerTransport).processor(pdpProcessor)); logger.info("Setting up the Thrift PDP server on port " + THRIFT_PDP_PORT); pdpServer.serve(); } }).start(); }
From source file:puma.central.pdp.EmptyCentralPUMAPDP.java
public static void main(String[] args) { // initialize log4j BasicConfigurator.configure();//from w ww . jav a 2 s. c o m CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("ph", "policy-home", true, "The folder where to find the policy file given with the given policy id. " + "For default operation, this folder should contain the central PUMA policy (called " + CENTRAL_PUMA_POLICY_FILENAME + ")"); options.addOption("pid", "policy-id", true, "The id of the policy to be evaluated on decision requests. Default value: " + GLOBAL_PUMA_POLICY_ID + ")"); options.addOption("s", "log-disabled", true, "Verbose mode (true/false)"); String policyHome = ""; String policyId = ""; // read command line try { CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Simple PDP Test", options); return; } if (line.hasOption("policy-home")) { policyHome = line.getOptionValue("policy-home"); } else { logger.log(Level.WARNING, "Incorrect arguments given."); return; } if (line.hasOption("log-disabled") && Boolean.parseBoolean(line.getOptionValue("log-disabled"))) { logger.log(Level.INFO, "Now switching to silent mode"); LogManager.getLogManager().getLogger("").setLevel(Level.WARNING); //LogManager.getLogManager().reset(); } if (line.hasOption("policy-id")) { policyId = line.getOptionValue("policy-id"); } else { logger.log(Level.INFO, "Using default policy id: " + GLOBAL_PUMA_POLICY_ID); policyId = GLOBAL_PUMA_POLICY_ID; } } catch (ParseException e) { logger.log(Level.WARNING, "Incorrect arguments given.", e); return; } // // STARTUP THE RMI SERVER // // if (System.getSecurityManager() == null) { // System.setSecurityManager(new SecurityManager()); // } EmptyCentralPUMAPDP pdp; try { pdp = new EmptyCentralPUMAPDP(policyHome, policyId); } catch (IOException e) { logger.log(Level.SEVERE, "FAILED to set up the CentralPUMAPDP. Quitting.", e); return; } try { Registry registry; try { registry = LocateRegistry.createRegistry(RMI_REGISITRY_PORT); logger.info("Created new RMI registry"); } catch (RemoteException e) { // MDC: I hope this means the registry already existed. registry = LocateRegistry.getRegistry(RMI_REGISITRY_PORT); logger.info("Reusing existing RMI registry"); } CentralPUMAPDPRemote stub = (CentralPUMAPDPRemote) UnicastRemoteObject.exportObject(pdp, 0); registry.bind(CENTRAL_PUMA_PDP_RMI_NAME, stub); logger.info( "Central PUMA PDP up and running (available using RMI with name \"central-puma-pdp\" on RMI registry port " + RMI_REGISITRY_PORT + ")"); Thread.sleep(100); // MDC: vroeger eindigde de Thread om n of andere reden, dit lijkt te werken... } catch (Exception e) { logger.log(Level.SEVERE, "FAILED to set up PDP as RMI server", e); } // // STARTUP THE THRIFT PEP SERVER // //logger.log(Level.INFO, "Not setting up the Thrift server"); // set up server // PEPServer handler = new PEPServer(new CentralPUMAPEP(pdp)); // RemotePEPService.Processor<PEPServer> processor = new RemotePEPService.Processor<PEPServer>(handler); // TServerTransport serverTransport; // try { // serverTransport = new TServerSocket(THRIFT_PEP_PORT); // } catch (TTransportException e) { // e.printStackTrace(); // return; // } // TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor)); // System.out.println("Setting up the Thrift PEP server on port " + THRIFT_PEP_PORT); // server.serve(); // // STARTUP THE THRIFT PEP SERVER // //logger.log(Level.INFO, "Not setting up the Thrift server"); // set up server RemotePDPService.Processor<EmptyCentralPUMAPDP> pdpProcessor = new RemotePDPService.Processor<EmptyCentralPUMAPDP>( pdp); TServerTransport pdpServerTransport; try { pdpServerTransport = new TServerSocket(THRIFT_PDP_PORT); } catch (TTransportException e) { e.printStackTrace(); return; } TServer pdpServer = new TSimpleServer(new TServer.Args(pdpServerTransport).processor(pdpProcessor)); System.out.println("Setting up the Thrift PDP server on port " + THRIFT_PDP_PORT); pdpServer.serve(); }
From source file:pw.phylame.gaf.cli.CApplication.java
protected void onOptionError(ParseException ex) { ex.printStackTrace(); exit(-1); }
From source file:pyromaniac.AcaciaMain.java
/** * The main method.//from w w w .j a va 2s . co m * * @param args the arguments */ @SuppressWarnings("static-access") public static void main(String[] args) { AcaciaMain am = new AcaciaMain(); Options options = new Options(); OptionGroup runType = new OptionGroup(); Option genConfigFile = OptionBuilder.withArgName("file").hasArg() .withDescription("Write default config to this file").create("g"); Option runFromConfig = OptionBuilder.withArgName("file").hasArg() .withDescription("Run Acacia with this config").create("c"); Option runGUI = OptionBuilder.withDescription("Run Acacia GUI").create("u"); Option help = OptionBuilder.withDescription("Show this help message").create("h"); Option version = OptionBuilder.withDescription("Version").create("v"); Option property = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator() .withDescription("use value for given property [when running from command line]").create("D"); runType.addOption(genConfigFile); runType.addOption(runFromConfig); runType.addOption(runGUI); runType.addOption(help); runType.addOption(version); runType.addOption(property); //this indicates the user is running from the command line without a config. options.addOptionGroup(runType); try { CommandLineParser parser = new PosixParser(); CommandLine clObj = parser.parse(options, args); if (!(clObj.hasOption('g') ^ clObj.hasOption('c') ^ clObj.hasOption('u') ^ clObj.hasOption('D') ^ clObj.hasOption('v'))) { usage(options); } if (clObj.hasOption('g')) { String config = clObj.getOptionValue('g'); am.generateConfig(config); System.exit(0); } else if (clObj.hasOption('c')) { String config = clObj.getOptionValue('c'); HashMap<String, String> settings = am.loadConfigFromFile(config); am.runAcacia(settings); } else if (clObj.hasOption('u')) { am.runAcacia(null); } else if (clObj.hasOption('v')) { System.out.println("Acacia version: " + AcaciaEngine.getVersion()); System.exit(0); } else if (clObj.hasOption('D')) { //running from command line... HashMap<String, String> settings = am.populateSettingsFromCommandLine(clObj); am.runAcacia(settings); } else { usage(options); } } catch (ParseException pe) { System.out.println(pe.getMessage()); pe.printStackTrace(); usage(options); } catch (Exception e) { e.printStackTrace(); am.cleanExit(null, e); } }
From source file:qa.qcri.qnoise.Qnoise.java
public static void main(String[] args) { options = createQnoiseOption();//from w ww .ja v a2 s . co m CommandLineParser parser = new GnuParser(); CSVReader reader = null; CSVWriter writer = null; try { CommandLine line = parser.parse(options, args); if (line.hasOption("v")) { Tracer.setVerbose(true); } final String inputFileName = line.getOptionValue("f"); if (Files.notExists(Paths.get(inputFileName))) { throw new FileNotFoundException("Input file " + inputFileName + " does not exist."); } JsonReader jsonReader = new JsonReader( new InputStreamReader(new FileInputStream(inputFileName), Charset.forName("UTF-8"))); GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(NoiseJsonAdapter.class, new NoiseJsonAdapterDeserializer()); gson.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); NoiseJsonAdapter adapter = gson.create().fromJson(jsonReader, NoiseJsonAdapter.class); reader = new CSVReader(new FileReader(adapter.getInputFile()), adapter.getCsvSeparator()); DataProfile profile = DataProfile.readData(reader, adapter.getSchema()); final String outputFileName = line.getOptionValue("o"); writer = new CSVWriter(new FileWriter(outputFileName), adapter.getCsvSeparator(), CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER); QnoiseFacade.inject(profile, adapter.getSpecs(), new IAction<NoiseContext>() { @Override public void act(NoiseContext context, HashMap<String, Object> extras) { context.report.appendMetric(NoiseReport.Metric.InputFilePath, inputFileName); context.report.appendMetric(NoiseReport.Metric.OutputFilePath, outputFileName); context.report.saveToFile(context.spec.logFile); context.report.print(); } }); profile.writeData(writer); } catch (MissingOptionException me) { printHelp(); } catch (ParseException ex) { ex.printStackTrace(); printHelp(); } catch (Exception ex) { tracer.println("Exception : " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (Exception ex) { } } }
From source file:rapture.config.ParameterValueReader.java
@Override public String getValue(String parameter) { String value = null;/* w w w . j a va2 s . co m*/ try { if (line == null) { line = new PosixParser().parse(options, args); } if (line.hasOption(parameter)) { value = line.getOptionValue(parameter, ""); //Adding the second param (defaultValue) handles the scenario of an option with no argument. } } catch (ParseException e) { log.debug("cannot parse command line options " + e.getMessage()); log.trace(ExceptionToString.format(e)); e.printStackTrace(); } // If cmd line option not present try environment if (value == null) { String envName = envMap.get(parameter); if (envName != null) value = envReader.getValue(envName); } // If environmental variable not defined try property reader if (value == null) { String propName = propMap.get(parameter); if (propName != null) value = envReader.getValue(propName); } return value; }
From source file:ru.icc.cells.ssdc.App.java
@SuppressWarnings("static-access") private static void parseCommandLineParams(String[] args) { // Creating command line parameters Option inputExcelFileOpt = OptionBuilder.withArgName("excel file").hasArg() .withDescription("an input excel workbook (*.xlsx) file").isRequired().create("i"); Option sheetIndexesOpt = OptionBuilder.withArgName("sheet indexes").hasArg() .withDescription("sheet indexes (e.g. \"0-2,4,5,7-10\") in the input excel workbook").create("s"); Option drlFileOpt = OptionBuilder.withArgName("drl or dslr file").hasArg() .withDescription("a rule (*.drl or *.dslr) file").isRequired().create("k"); Option catDirectoryOpt = OptionBuilder.withArgName("cat directory").hasArg() .withDescription("directory with *.cat files").create("c"); Option withoutSuperscriptOpt = OptionBuilder.withArgName("true|false").hasArg() .withDescription("use true to ignore superscript text in cells").create("ss"); Option useCellValueOpt = OptionBuilder.withArgName("true|false").hasArg() .withDescription("use true to use cell values as text").create("v"); Option outputDirectoryOpt = OptionBuilder.withArgName("output directory").hasArg() .withDescription("a directory for outputting results").create("o"); Option debuggingModeOpt = OptionBuilder.withArgName("true|false").hasArg() .withDescription("use true to turn on debugging mode").create("m"); Options options = new Options(); options.addOption(inputExcelFileOpt); options.addOption(sheetIndexesOpt);//from ww w . j a va 2 s.c o m options.addOption(drlFileOpt); options.addOption(catDirectoryOpt); options.addOption(withoutSuperscriptOpt); options.addOption(useCellValueOpt); options.addOption(outputDirectoryOpt); options.addOption(debuggingModeOpt); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); String inputExcelFileParam = cmd.getOptionValue(inputExcelFileOpt.getOpt()); inputExcelFile = parseInputExcelFileParam(inputExcelFileParam); String sheetIndexesParam = cmd.getOptionValue(sheetIndexesOpt.getOpt()); sheetIndexes = parseSheetIndexesParam(sheetIndexesParam); String drlFileParam = cmd.getOptionValue(drlFileOpt.getOpt()); drlFile = parseDrlFileParam(drlFileParam); String catDirectoryParam = cmd.getOptionValue(catDirectoryOpt.getOpt()); catDirectory = parseCatDirectoryParam(catDirectoryParam); String withoutSuperscriptParam = cmd.getOptionValue(withoutSuperscriptOpt.getOpt()); withoutSuperscript = parseWithoutSuperscriptParam(withoutSuperscriptParam); String useCellValuParam = cmd.getOptionValue(useCellValueOpt.getOpt()); useCellValue = parseUseCellValueParam(useCellValuParam); String outputDirectoryParam = cmd.getOptionValue(outputDirectoryOpt.getOpt()); outputDirectory = parseOutputDirectoryParam(outputDirectoryParam); String debuggingModeParam = cmd.getOptionValue(debuggingModeOpt.getOpt()); debuggingMode = parseDebuggingModeParam(debuggingModeParam); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } }
From source file:runtime.daemonmanager.CLOptions.java
@SuppressWarnings("static-access") public void parseCommandLineArgs(String[] args) { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(new Option(DMConstants.HELP_OPT, DMConstants.HELP, false, DMMessages.CMD_OPT_HELP)); options.addOption(new Option(DMConstants.BOOT_OPT, DMConstants.BOOT, false, DMMessages.CMD_OPT_BOOT)); options.addOption(new Option(DMConstants.HALT_OPT, DMConstants.HALT, false, DMMessages.CMD_OPT_HALT)); options.addOption(new Option(DMConstants.CLEAN_OPT, DMConstants.CLEAN, false, DMMessages.CMD_OPT_CLEAN)); options.addOption(new Option(DMConstants.STATUS_OPT, DMConstants.STATUS, false, DMMessages.CMD_OPT_STATUS)); options.addOption(new Option(DMConstants.INFO_OPT, DMConstants.INFO, false, DMMessages.CMD_OPT_INFO)); options.addOption(new Option(DMConstants.MACHINE_FILE_OPT, DMConstants.MACHINE_FILE, true, DMMessages.CMD_OPT_MACHINE_FILE)); options.addOption(OptionBuilder.withLongOpt(DMConstants.HOSTS).hasArgs() .withDescription(DMMessages.CMD_OPT_HOSTS).withValueSeparator(' ').create(DMConstants.HOSTS_OPT)); options.addOption(new Option(DMConstants.THREAD_COUNT_OPT, DMConstants.THREAD_COUNT, true, DMMessages.CMD_OPT_THREAD_COUNT)); options.addOption(new Option(DMConstants.PORT_OPT, DMConstants.PORT, true, DMMessages.CMD_OPT_PORT)); options.addOption(//from ww w. ja va 2 s . c o m new Option(DMConstants.WIN_BOOT_OPT, DMConstants.WIN_BOOT, false, DMMessages.CMD_OPT_BOOT)); options.addOption( new Option(DMConstants.WIN_HALT_OPT, DMConstants.WIN_HALT, false, DMMessages.CMD_OPT_HALT)); try { CommandLine line = parser.parse(options, args); if (line.hasOption(DMConstants.HELP)) this.setCmdType(DMConstants.HELP); else if (line.hasOption(DMConstants.BOOT)) this.setCmdType(DMConstants.BOOT); else if (line.hasOption(DMConstants.HALT)) this.setCmdType(DMConstants.HALT); else if (line.hasOption(DMConstants.STATUS)) this.setCmdType(DMConstants.STATUS); else if (line.hasOption(DMConstants.INFO)) this.setCmdType(DMConstants.INFO); else if (line.hasOption(DMConstants.CLEAN)) this.setCmdType(DMConstants.CLEAN); else if (line.hasOption(DMConstants.WIN_BOOT)) this.setCmdType(DMConstants.WIN_BOOT); else if (line.hasOption(DMConstants.WIN_HALT)) this.setCmdType(DMConstants.WIN_HALT); if (line.hasOption(DMConstants.HOSTS)) { String[] hosts = line.getOptionValues(DMConstants.HOSTS); for (String host : hosts) { this.getMachineList().add(host); this.setThreadCount(this.getMachineList().size()); } } else if (line.hasOption(DMConstants.MACHINE_FILE)) { String machineFilePath = line.getOptionValue(DMConstants.MACHINE_FILE); this.setMachineFilePath(machineFilePath); int nSize = MPJUtil.readMachineFile(machineFilePath).size(); int nThreads = 1; if (nSize > 1) nThreads = (int) (Math.log(nSize) / Math.log(2)); this.setThreadCount(nThreads); } if (line.hasOption(DMConstants.THREAD_COUNT)) { int nThreads = Integer.parseInt(line.getOptionValue(DMConstants.THREAD_COUNT)); this.setThreadCount(nThreads); } if (line.hasOption(DMConstants.PORT)) { Integer port = Integer.parseInt(line.getOptionValue(DMConstants.PORT)); this.setPort(port.toString()); } } catch (ParseException e) { e.printStackTrace(); } }