List of usage examples for org.apache.commons.cli CommandLineParser parse
CommandLine parse(Options options, String[] arguments) throws ParseException;
From source file:com.twentyn.patentTextProcessor.WordCountProcessor.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();/*from www . j av a 2 s .c om*/ Options opts = new Options(); opts.addOption(Option.builder("i").longOpt("input").hasArg().required() .desc("Input file or directory to score").build()); opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build()); opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build()); HelpFormatter helpFormatter = new HelpFormatter(); CommandLineParser cmdLineParser = new DefaultParser(); CommandLine cmdLine = null; try { cmdLine = cmdLineParser.parse(opts, args); } catch (ParseException e) { System.out.println("Caught exception when parsing command line: " + e.getMessage()); helpFormatter.printHelp("WordCountProcessor", opts); System.exit(1); } if (cmdLine.hasOption("help")) { helpFormatter.printHelp("DocumentIndexer", opts); System.exit(0); } String inputFileOrDir = cmdLine.getOptionValue("input"); File splitFileOrDir = new File(inputFileOrDir); if (!(splitFileOrDir.exists())) { LOGGER.error("Unable to find directory at " + inputFileOrDir); System.exit(1); } WordCountProcessor wcp = new WordCountProcessor(); PatentCorpusReader corpusReader = new PatentCorpusReader(wcp, splitFileOrDir); corpusReader.readPatentCorpus(); }
From source file:edu.usf.cutr.obascs.OBASCSMain.java
public static void main(String[] args) { String logLevel = null;// ww w . j a v a 2s. c om String outputFilePath = null; String inputFilePath = null; String spreadSheetId = null; Logger logger = Logger.getInstance(); Options options = CommandLineUtil.createCommandLineOptions(); CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, args); logLevel = CommandLineUtil.getLogLevel(cmd); logger.setup(logLevel); outputFilePath = CommandLineUtil.getOutputPath(cmd); spreadSheetId = CommandLineUtil.getSpreadSheetId(cmd); inputFilePath = CommandLineUtil.getInputPath(cmd); } catch (ParseException e1) { logger.logError(e1); } catch (FileNotFoundException e) { logger.logError(e); } Map<String, String> agencyMap = null; try { agencyMap = FileUtil.readAgencyInformantions(inputFilePath); } catch (IOException e1) { logger.logError(e1); } logger.log("Consolidation started..."); logger.log("Trying as public url"); ListFeed listFeed = null; Boolean authRequired = false; try { listFeed = SpreadSheetReader.readPublicSpreadSheet(spreadSheetId); } catch (IOException e) { logger.logError(e); } catch (ServiceException e) { logger.log("Authentication Required"); authRequired = true; } if (listFeed == null && authRequired == true) { Scanner scanner = new Scanner(System.in); String userName, password; logger.log("UserName:"); userName = scanner.nextLine(); logger.log("Password:"); password = scanner.nextLine(); scanner.close(); try { listFeed = SpreadSheetReader.readPrivateSpreadSheet(userName, password, spreadSheetId); } catch (IOException e) { logger.logError(e); } catch (ServiceException e) { logger.logError(e); } } if (listFeed != null) { //Creating consolidated stops String consolidatedString = FileConsolidator.consolidateFile(listFeed, agencyMap); try { FileUtil.writeToFile(consolidatedString, outputFilePath); } catch (FileNotFoundException e) { logger.logError(e); } //Creating sample stop consolidation script config file try { String path = ClassLoader.getSystemClassLoader() .getResource(GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE).getPath(); String configXml = FileUtil.readFile(URLUtil.trimSpace(path)); configXml = ConfigFileGenerator.generateStopConsolidationScriptConfigFile(configXml, agencyMap); path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE; FileUtil.writeToFile(configXml, path); } catch (IOException e) { logger.logError(e); } //Creating sample real-time config file try { String path = ClassLoader.getSystemClassLoader() .getResource(GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE).getPath(); String configXml = FileUtil.readFile(URLUtil.trimSpace(path)); configXml = ConfigFileGenerator.generateSampleRealTimeConfigFile(configXml, agencyMap); path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE; FileUtil.writeToFile(configXml, path); } catch (IOException e) { logger.logError(e); } } else { logger.logError("Cannot write files"); } logger.log("Consolidation finished..."); }
From source file:de.unirostock.sems.caro.CaRo.java
/** * The main method to be called by the command line. * // w ww .j a va 2s . c o m * @param args * the arguments */ public static void main(String[] args) { Options options = new Options(); options.addOption(new Option("h", "help", false, "print the help message")); options.addOption( Option.builder().longOpt("roca").desc("convert a research object into a combine archive").build()); options.addOption( Option.builder().longOpt("caro").desc("convert a combine archive into a research object").build()); options.addOption(Option.builder("i").longOpt("in").required().argName("FILE").hasArg() .desc("source container to be converted").build()); options.addOption(Option.builder("o").longOpt("out").required().argName("FILE").hasArg() .desc("target container to be created").build()); CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); if (line.hasOption("help")) { help(options, null); return; } } catch (ParseException e) { help(options, "Parsing of command line options failed. Reason: " + e.getMessage()); return; } File in = new File(line.getOptionValue("in")); File out = new File(line.getOptionValue("out")); if (!in.exists()) { help(options, "file " + in + " does not exist"); return; } if (out.exists()) { help(options, "file " + out + " already exist"); return; } if (line.hasOption("caro") && line.hasOption("roca")) { help(options, "only one of --roca and --caro is allowed"); return; } CaRoConverter conv = null; if (line.hasOption("caro")) conv = new CaToRo(in); else if (line.hasOption("roca")) conv = new RoToCa(in); else { help(options, "you need to either supply --roca or --caro"); return; } conv.convertTo(out); if (conv.hasErrors()) System.err.println("There were errors!"); if (conv.hasWarnings()) System.err.println("There were warnings!"); List<CaRoNotification> notifications = conv.getNotifications(); for (CaRoNotification note : notifications) System.out.println(note); }
From source file:it.tizianofagni.sparkboost.AdaBoostMHLearnerExe.java
public static void main(String[] args) { Options options = new Options(); options.addOption("b", "binaryProblem", false, "Indicate if the input dataset contains a binary problem and not a multilabel one"); options.addOption("z", "labels0based", false, "Indicate if the labels IDs in the dataset to classifyLibSvmWithResults are already assigned in the range [0, numLabels-1] included"); options.addOption("l", "enableSparkLogging", false, "Enable logging messages of Spark"); options.addOption("w", "windowsLocalModeFix", true, "Set the directory containing the winutils.exe command"); options.addOption("dp", "documentPartitions", true, "The number of document partitions"); options.addOption("fp", "featurePartitions", true, "The number of feature partitions"); options.addOption("lp", "labelPartitions", true, "The number of label partitions"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null;/*from www . ja v a 2s. c o m*/ String[] remainingArgs = null; try { cmd = parser.parse(options, args); remainingArgs = cmd.getArgs(); if (remainingArgs.length != 5) throw new ParseException("You need to specify all mandatory parameters"); } catch (ParseException e) { System.out.println("Parsing failed. Reason: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(AdaBoostMHLearnerExe.class.getSimpleName() + " [OPTIONS] <inputFile> <outputFile> <numIterations> <sparkMaster> <parallelismDegree>", options); System.exit(-1); } boolean binaryProblem = false; if (cmd.hasOption("b")) binaryProblem = true; boolean labels0Based = false; if (cmd.hasOption("z")) labels0Based = true; boolean enablingSparkLogging = false; if (cmd.hasOption("l")) enablingSparkLogging = true; if (cmd.hasOption("w")) { System.setProperty("hadoop.home.dir", cmd.getOptionValue("w")); } String inputFile = remainingArgs[0]; String outputFile = remainingArgs[1]; int numIterations = Integer.parseInt(remainingArgs[2]); String sparkMaster = remainingArgs[3]; int parallelismDegree = Integer.parseInt(remainingArgs[4]); long startTime = System.currentTimeMillis(); // Disable Spark logging. if (!enablingSparkLogging) { Logger.getLogger("org").setLevel(Level.OFF); Logger.getLogger("akka").setLevel(Level.OFF); } // Create and configure Spark context. SparkConf conf = new SparkConf().setAppName("Spark AdaBoost.MH learner"); JavaSparkContext sc = new JavaSparkContext(conf); // Create and configure learner. AdaBoostMHLearner learner = new AdaBoostMHLearner(sc); learner.setNumIterations(numIterations); if (cmd.hasOption("dp")) { learner.setNumDocumentsPartitions(Integer.parseInt(cmd.getOptionValue("dp"))); } if (cmd.hasOption("fp")) { learner.setNumFeaturesPartitions(Integer.parseInt(cmd.getOptionValue("fp"))); } if (cmd.hasOption("lp")) { learner.setNumLabelsPartitions(Integer.parseInt(cmd.getOptionValue("lp"))); } // Build classifier with MPBoost learner. BoostClassifier classifier = learner.buildModel(inputFile, labels0Based, binaryProblem); // Save classifier to disk. DataUtils.saveModel(sc, classifier, outputFile); long endTime = System.currentTimeMillis(); System.out.println("Execution time: " + (endTime - startTime) + " milliseconds."); }
From source file:cz.deco.Main.java
public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); DecoContextImpl context = new DecoContextImpl(); Options options = getOptions();/* ww w . j a v a 2 s .co m*/ CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException exp) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar deco.jar", options); return; } String source = cmd.getOptionValue("s"); String target = cmd.getOptionValue("t"); String plan = cmd.getOptionValue("p"); String temp = cmd.getOptionValue("d"); context.setOutputArchive(new File(target).getAbsoluteFile().toPath()); context.setApplicationArchive(new File(source).getAbsoluteFile().toPath()); Path temporaryDir; if (cmd.hasOption("d")) { temporaryDir = new File(temp).getAbsoluteFile().toPath(); } else { temporaryDir = getTempDirectory(); } context.setTemporaryDir(temporaryDir); context.setDeploymentPlan(new File(plan).getAbsoluteFile().toPath()); new Application().doWork(context); cleanUp(temporaryDir); }
From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java
/** * Main application to be run when this CygnusApplication is invoked. The only differences with the original one * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in * the command line.//from w ww .ja va2 s . co m * @param args */ public static void main(String[] args) { try { Options options = new Options(); Option option = new Option("n", "name", true, "the name of this agent"); option.setRequired(true); options.addOption(option); option = new Option("f", "conf-file", true, "specify a conf file"); option.setRequired(true); options.addOption(option); option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed"); options.addOption(option); option = new Option("h", "help", false, "display help text"); options.addOption(option); option = new Option("p", "mgmt-if-port", true, "the management interface port"); option.setRequired(false); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); File configurationFile = new File(commandLine.getOptionValue('f')); String agentName = commandLine.getOptionValue('n'); boolean reload = !commandLine.hasOption("no-reload-conf"); if (commandLine.hasOption('h')) { new HelpFormatter().printHelp("flume-ng agent", options, true); return; } // if int mgmtIfPort = 8081; // default value if (commandLine.hasOption('p')) { mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue(); } // if // the following is to ensure that by default the agent will fail on startup if the file does not exist if (!configurationFile.exists()) { // if command line invocation, then need to fail fast if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) { String path = configurationFile.getPath(); try { path = configurationFile.getCanonicalPath(); } catch (IOException ex) { logger.error("Failed to read canonical path for file: " + path, ex); } // try catch throw new ParseException("The specified configuration file does not exist: " + path); } // if } // if List<LifecycleAware> components = Lists.newArrayList(); CygnusApplication application; if (reload) { EventBus eventBus = new EventBus(agentName + "-event-bus"); PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider( agentName, configurationFile, eventBus, 30); components.add(configurationProvider); application = new CygnusApplication(components, mgmtIfPort); eventBus.register(application); } else { PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider( agentName, configurationFile); application = new CygnusApplication(mgmtIfPort); application.handleConfigurationEvent(configurationProvider.getConfiguration()); } // if else application.start(); final CygnusApplication appReference = application; Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") { @Override public void run() { appReference.stop(); } // run }); } catch (Exception e) { logger.error("A fatal error occurred while running. Exception follows.", e); } // try catch }
From source file:fr.cnrs.sharp.Main.java
public static void main(String args[]) { Options options = new Options(); Option versionOpt = new Option("v", "version", false, "print the version information and exit"); Option helpOpt = new Option("h", "help", false, "print the help"); Option inProvFileOpt = OptionBuilder.withArgName("input_PROV_file_1> ... <input_PROV_file_n") .withLongOpt("input_PROV_files").withDescription("The list of PROV input files, in RDF Turtle.") .hasArgs().create("i"); Option inRawFileOpt = OptionBuilder.withArgName("input_raw_file_1> ... <input_raw_file_n") .withLongOpt("input_raw_files") .withDescription(/*from ww w . j a v a 2 s .c o m*/ "The list of raw files to be fingerprinted and possibly interlinked with owl:sameAs.") .hasArgs().create("ri"); Option summaryOpt = OptionBuilder.withArgName("summary").withLongOpt("summary") .withDescription("Materialization of wasInfluencedBy relations.").create("s"); options.addOption(inProvFileOpt); options.addOption(inRawFileOpt); options.addOption(versionOpt); options.addOption(helpOpt); options.addOption(summaryOpt); String header = "SharpTB is a tool to maturate provenance based on PROV inferences"; String footer = "\nPlease report any issue to alban.gaignard@univ-nantes.fr"; try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpTB", header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { logger.info("SharpTB version 0.1.0"); System.exit(0); } if (cmd.hasOption("ri")) { String[] inFiles = cmd.getOptionValues("ri"); Model model = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { //1. fingerprint try { model.add(Interlinking.fingerprint(p)); } catch (IOException e) { logger.error("Cannot fingerprint file " + inFile); } } } //2. genSameAs Model sameAs = Interlinking.generateSameAs(model); sameAs.write(System.out, "TTL"); } if (cmd.hasOption("i")) { String[] inFiles = cmd.getOptionValues("i"); Model data = ModelFactory.createDefaultModel(); for (String inFile : inFiles) { Path p = Paths.get(inFile); if (!p.toFile().isFile()) { logger.error("Cannot find file " + inFile); System.exit(1); } else { RDFDataMgr.read(data, inFile, Lang.TTL); } } Model res = Harmonization.harmonizeProv(data); try { Path pathInfProv = Files.createTempFile("PROV-inf-tgd-egd-", ".ttl"); res.write(new FileWriter(pathInfProv.toFile()), "TTL"); System.out.println("Harmonized PROV written to file " + pathInfProv.toString()); //if the summary option is activated, then save the subgraph and generate a visualization if (cmd.hasOption("s")) { String queryInfluence = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \n" + "PREFIX prov: <http://www.w3.org/ns/prov#> \n" + "CONSTRUCT { \n" + " ?x ?p ?y .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "} WHERE {\n" + " ?x ?p ?y .\n" + " FILTER (?p IN (prov:wasInfluencedBy)) .\n" + " ?x rdfs:label ?lx .\n" + " ?y rdfs:label ?ly .\n" + "}"; Query query = QueryFactory.create(queryInfluence); QueryExecution queryExec = QueryExecutionFactory.create(query, res); Model summary = queryExec.execConstruct(); queryExec.close(); Util.writeHtmlViz(summary); } } catch (IOException ex) { logger.error("Impossible to write the harmonized provenance file."); System.exit(1); } } else { // logger.info("Please fill the -i input parameter."); // HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp("SharpTB", header, options, footer, true); // System.exit(0); } } catch (ParseException ex) { logger.error("Error while parsing command line arguments. Please check the following help:"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SharpToolBox", header, options, footer, true); System.exit(1); } }
From source file:fr.inria.atlanmod.atl_mr.utils.NeoEMFHBaseMigrator.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input file, both of xmi and zxmi extensions are supported"); inputOpt.setArgs(1);/*from ww w .j a v a 2 s . c o m*/ inputOpt.setRequired(true); Option outputOpt = OptionBuilder.create(OUT); outputOpt.setArgName("OUTPUT"); outputOpt.setDescription("Output HBase resource URI"); outputOpt.setArgs(1); outputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(E_PACKAGE); inClassOpt.setArgName("METAMODEL"); inClassOpt.setDescription("URI of the ecore Metamodel"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); options.addOption(inputOpt); options.addOption(outputOpt); options.addOption(inClassOpt); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN)); URI targetUri = URI.createURI(commandLine.getOptionValue(OUT)); URI metamodelUri = URI.createFileURI(commandLine.getOptionValue(E_PACKAGE)); NeoEMFHBaseMigrator.class.getClassLoader().loadClass(commandLine.getOptionValue(E_PACKAGE)) .getMethod("init").invoke(null); //org.eclipse.gmt.modisco.java.kyanos.impl.JavaPackageImpl.init(); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi", new XMIResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(KyanosURI.KYANOS_HBASE_SCHEME, KyanosResourceFactory.eINSTANCE); //Registering the metamodel // Resource MMResource = resourceSet.createResource(metamodelUri); // MMResource.load(Collections.EMPTY_MAP); // ATLMRUtils.registerPackages(resourceSet, MMResource); //Loading the XMI resource Resource sourceResource = resourceSet.createResource(sourceUri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if ("zxmi".equals(sourceUri.fileExtension())) { loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE); } Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}", ATLMRUtils.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Loading source resource"); sourceResource.load(loadOpts); LOG.log(Level.INFO, "Source resource loaded"); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}", ATLMRUtils.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", ATLMRUtils.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); Resource targetResource = resourceSet.createResource(targetUri); Map<String, Object> saveOpts = new HashMap<String, Object>(); targetResource.save(saveOpts); LOG.log(Level.INFO, "Start moving elements"); targetResource.getContents().clear(); targetResource.getContents().addAll(sourceResource.getContents()); LOG.log(Level.INFO, "End moving elements"); LOG.log(Level.INFO, "Start saving"); targetResource.save(saveOpts); LOG.log(Level.INFO, "Saved"); if (targetResource instanceof KyanosHbaseResourceImpl) { KyanosHbaseResourceImpl.shutdownWithoutUnload((KyanosHbaseResourceImpl) targetResource); } else { targetResource.unload(); } } catch (ParseException e) { ATLMRUtils.showError(e.toString()); ATLMRUtils.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { ATLMRUtils.showError(e.toString()); e.printStackTrace(); } }
From source file:DokeosConverter.java
public static void main(String[] arguments) throws Exception { CommandLineParser commandLineParser = new PosixParser(); CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments); int port = SocketOpenOfficeConnection.DEFAULT_PORT; if (commandLine.hasOption(OPTION_PORT.getOpt())) { port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt())); }/* w w w . j a va 2s . c o m*/ String outputFormat = null; if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) { outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt()); } boolean verbose = false; if (commandLine.hasOption(OPTION_VERBOSE.getOpt())) { verbose = true; } String dokeosMode = "woogie"; if (commandLine.hasOption(OPTION_DOKEOS_MODE.getOpt())) { dokeosMode = commandLine.getOptionValue(OPTION_DOKEOS_MODE.getOpt()); } int width = 800; if (commandLine.hasOption(OPTION_WIDTH.getOpt())) { width = Integer.parseInt(commandLine.getOptionValue(OPTION_WIDTH.getOpt())); } int height = 600; if (commandLine.hasOption(OPTION_HEIGHT.getOpt())) { height = Integer.parseInt(commandLine.getOptionValue(OPTION_HEIGHT.getOpt())); } String[] fileNames = commandLine.getArgs(); if ((outputFormat == null && fileNames.length != 2 && dokeosMode != null) || fileNames.length < 1) { String syntax = "convert [options] input-file output-file; or\n" + "[options] -f output-format input-file [input-file...]"; HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(syntax, OPTIONS); System.exit(EXIT_CODE_TOO_FEW_ARGS); } OpenOfficeConnection connection = new DokeosSocketOfficeConnection(port); try { if (verbose) { System.out.println("-- connecting to OpenOffice.org on port " + port); } connection.connect(); } catch (ConnectException officeNotRunning) { System.err.println( "ERROR: connection failed. Please make sure OpenOffice.org is running and listening on port " + port + "."); System.exit(EXIT_CODE_CONNECTION_FAILED); } try { // choose the good constructor to deal with the conversion DocumentConverter converter; if (dokeosMode.equals("oogie")) { converter = new OogieDocumentConverter(connection, new DokeosDocumentFormatRegistry(), width, height); } else if (dokeosMode.equals("woogie")) { converter = new WoogieDocumentConverter(connection, new DokeosDocumentFormatRegistry(), width, height); } else { converter = new OpenOfficeDocumentConverter(connection); } if (outputFormat == null) { File inputFile = new File(fileNames[0]); File outputFile = new File(fileNames[1]); convertOne(converter, inputFile, outputFile, verbose); } else { for (int i = 0; i < fileNames.length; i++) { File inputFile = new File(fileNames[i]); File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat); convertOne(converter, inputFile, outputFile, verbose); } } } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) { connection.disconnect(); System.err.println("ERROR: conversion failed."); System.exit(EXIT_CODE_CONVERSION_FAILED); } finally { if (verbose) { System.out.println("-- disconnecting"); } connection.disconnect(); } }
From source file:com.mindquarry.management.user.UserManagementClient.java
public static void main(String[] args) { log = LogFactory.getLog(UserManagementClient.class); log.info("Starting user management client..."); //$NON-NLS-1$ // parse command line arguments CommandLine line = null;/*from ww w. ja v a2 s . com*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments line = parser.parse(options, args); } catch (ParseException e) { // oops, something went wrong log.error("Parsing of command line failed."); //$NON-NLS-1$ printUsage(); return; } // retrieve login data System.out.print("Please enter your login ID: "); //$NON-NLS-1$ String user = readString(); user = user.trim(); System.out.print("Please enter your new password: "); //$NON-NLS-1$ String password = readString(); password = password.trim(); password = new String(DigestUtils.md5(password)); password = new String(Base64.encodeBase64(password.getBytes())); // start PWD change client UserManagementClient manager = new UserManagementClient(); try { if (line.hasOption(O_DEL)) { manager.deleteUser(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password); } else { manager.changePwd(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password); } } catch (Exception e) { log.error("Error while applying password changes.", e); //$NON-NLS-1$ } log.info("User management client finished successfully."); //$NON-NLS-1$ }