List of usage examples for java.lang String toUpperCase
public String toUpperCase()
From source file:com.metamx.druid.utils.ExposeS3DataSource.java
public static void main(String[] args) throws ServiceException, IOException, NoSuchAlgorithmException { CLI cli = new CLI(); cli.addOption(new RequiredOption(null, "s3Bucket", true, "s3 bucket to pull data from")); cli.addOption(new RequiredOption(null, "s3Path", true, "base input path in s3 bucket. Everything until the date strings.")); cli.addOption(new RequiredOption(null, "timeInterval", true, "ISO8601 interval of dates to index")); cli.addOption(new RequiredOption(null, "granularity", true, String.format( "granularity of index, supported granularities: [%s]", Arrays.asList(Granularity.values())))); cli.addOption(new RequiredOption(null, "zkCluster", true, "Cluster string to connect to ZK with.")); cli.addOption(new RequiredOption(null, "zkBasePath", true, "The base path to register index changes to.")); CommandLine commandLine = cli.parse(args); if (commandLine == null) { return;//from w ww. ja va 2s.c o m } String s3Bucket = commandLine.getOptionValue("s3Bucket"); String s3Path = commandLine.getOptionValue("s3Path"); String timeIntervalString = commandLine.getOptionValue("timeInterval"); String granularity = commandLine.getOptionValue("granularity"); String zkCluster = commandLine.getOptionValue("zkCluster"); String zkBasePath = commandLine.getOptionValue("zkBasePath"); Interval timeInterval = new Interval(timeIntervalString); Granularity gran = Granularity.valueOf(granularity.toUpperCase()); final RestS3Service s3Client = new RestS3Service(new AWSCredentials( System.getProperty("com.metamx.aws.accessKey"), System.getProperty("com.metamx.aws.secretKey"))); ZkClient zkClient = new ZkClient(new ZkConnection(zkCluster), Integer.MAX_VALUE, new StringZkSerializer()); zkClient.waitUntilConnected(); for (Interval interval : gran.getIterable(timeInterval)) { log.info("Processing interval[%s]", interval); String s3DatePath = JOINER.join(s3Path, gran.toPath(interval.getStart())); if (!s3DatePath.endsWith("/")) { s3DatePath += "/"; } StorageObjectsChunk chunk = s3Client.listObjectsChunked(s3Bucket, s3DatePath, "/", 2000, null, true); TreeSet<String> commonPrefixes = Sets.newTreeSet(); commonPrefixes.addAll(Arrays.asList(chunk.getCommonPrefixes())); if (commonPrefixes.isEmpty()) { log.info("Nothing at s3://%s/%s", s3Bucket, s3DatePath); continue; } String latestPrefix = commonPrefixes.last(); log.info("Latest segments at [s3://%s/%s]", s3Bucket, latestPrefix); chunk = s3Client.listObjectsChunked(s3Bucket, latestPrefix, "/", 2000, null, true); Integer partitionNumber; if (chunk.getCommonPrefixes().length == 0) { partitionNumber = null; } else { partitionNumber = -1; for (String partitionPrefix : chunk.getCommonPrefixes()) { String[] splits = partitionPrefix.split("/"); partitionNumber = Math.max(partitionNumber, Integer.parseInt(splits[splits.length - 1])); } } log.info("Highest segment partition[%,d]", partitionNumber); if (partitionNumber == null) { final S3Object s3Obj = new S3Object(new S3Bucket(s3Bucket), String.format("%sdescriptor.json", latestPrefix)); updateWithS3Object(zkBasePath, s3Client, zkClient, s3Obj); } else { for (int i = partitionNumber; i >= 0; --i) { final S3Object partitionObject = new S3Object(new S3Bucket(s3Bucket), String.format("%s%s/descriptor.json", latestPrefix, i)); updateWithS3Object(zkBasePath, s3Client, zkClient, partitionObject); } } } }
From source file:MainClass.java
public static void main(String[] args) throws IOException { Charset charset = Charset.forName("ISO-8859-1"); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); ByteBuffer buffer = ByteBuffer.allocate(512); Selector selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new java.net.InetSocketAddress(8000)); server.configureBlocking(false);/* www .ja va 2s . com*/ SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT); for (;;) { selector.select(); Set keys = selector.selectedKeys(); for (Iterator i = keys.iterator(); i.hasNext();) { SelectionKey key = (SelectionKey) i.next(); i.remove(); if (key == serverkey) { if (key.isAcceptable()) { SocketChannel client = server.accept(); client.configureBlocking(false); SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ); clientkey.attach(new Integer(0)); } } else { SocketChannel client = (SocketChannel) key.channel(); if (!key.isReadable()) continue; int bytesread = client.read(buffer); if (bytesread == -1) { key.cancel(); client.close(); continue; } buffer.flip(); String request = decoder.decode(buffer).toString(); buffer.clear(); if (request.trim().equals("quit")) { client.write(encoder.encode(CharBuffer.wrap("Bye."))); key.cancel(); client.close(); } else { int num = ((Integer) key.attachment()).intValue(); String response = num + ": " + request.toUpperCase(); client.write(encoder.encode(CharBuffer.wrap(response))); key.attach(new Integer(num + 1)); } } } } }
From source file:com.ctriposs.rest4j.tools.idlcheck.Rest4JResourceModelCompatibilityChecker.java
@SuppressWarnings({ "static" }) public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); final String cmdLineSyntax = Rest4JResourceModelCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {/*from ww w. j a va2s.c o m*/ cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; } final StringBuilder allSummaries = new StringBuilder(); boolean result = true; for (int i = 1; i < targets.length; i += 2) { final Rest4JResourceModelCompatibilityChecker checker = new Rest4JResourceModelCompatibilityChecker(); checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH)); String prevTarget = targets[i - 1]; String currTarget = targets[i]; result &= checker.check(prevTarget, currTarget, compat); allSummaries.append(checker.getInfoMap().createSummary(prevTarget, currTarget)); } if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } System.exit(result ? 0 : 1); }
From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java
public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); final String cmdLineSyntax = Rest4JSnapshotCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {/*from w w w . ja v a2s. c om*/ cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; } final StringBuilder allSummaries = new StringBuilder(); boolean result = true; final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH); final Rest4JSnapshotCompatibilityChecker checker = new Rest4JSnapshotCompatibilityChecker(); checker.setResolverPath(resolverPath); for (int i = 1; i < targets.length; i += 2) { String prevTarget = targets[i - 1]; String currTarget = targets[i]; CompatibilityInfoMap infoMap = checker.check(prevTarget, currTarget, compat); result &= infoMap.isCompatible(compat); allSummaries.append(infoMap.createSummary(prevTarget, currTarget)); } if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } System.exit(result ? 0 : 1); }
From source file:com.linkedin.restli.tools.idlcheck.RestLiResourceModelCompatibilityChecker.java
public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); options.addOption(OptionBuilder.withLongOpt("report").withDescription( "Prints a report at the end of the execution that can be parsed for reporting to other tools") .create("report")); final String cmdLineSyntax = RestLiResourceModelCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {// w w w . j ava 2s . co m cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); return; } final StringBuilder allSummaries = new StringBuilder(); final RestLiResourceModelCompatibilityChecker checker = new RestLiResourceModelCompatibilityChecker(); for (int i = 1; i < targets.length; i += 2) { checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH)); String prevTarget = targets[i - 1]; String currTarget = targets[i]; checker.check(prevTarget, currTarget, compat); } allSummaries.append(checker.getInfoMap().createSummary()); if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } if (cmd.hasOption("report")) { System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport()); System.exit(0); } System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1); }
From source file:com.linkedin.restli.tools.snapshot.check.RestLiSnapshotCompatibilityChecker.java
public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); options.addOption(OptionBuilder.withLongOpt("report").withDescription( "Prints a report at the end of the execution that can be parsed for reporting to other tools") .create("report")); final String cmdLineSyntax = RestLiSnapshotCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {/*from w ww . ja v a 2 s . c om*/ cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); return; } final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH); final RestLiSnapshotCompatibilityChecker checker = new RestLiSnapshotCompatibilityChecker(); checker.setResolverPath(resolverPath); for (int i = 1; i < targets.length; i += 2) { String prevTarget = targets[i - 1]; String currTarget = targets[i]; checker.checkCompatibility(prevTarget, currTarget, compat, prevTarget.endsWith(".restspec.json")); } String summary = checker.getInfoMap().createSummary(); if (compat != CompatibilityLevel.OFF && summary.length() > 0) { System.out.println(summary); } if (cmd.hasOption("report")) { System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport()); System.exit(0); } System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1); }
From source file:de.zazaz.iot.bosch.indego.util.CmdLineTool.java
public static void main(String[] args) { Options options = new Options(); StringBuilder commandList = new StringBuilder(); for (DeviceCommand cmd : DeviceCommand.values()) { if (commandList.length() > 0) { commandList.append(", "); }// w w w . j a v a2s .c o m commandList.append(cmd.toString()); } options.addOption(Option // .builder() // .longOpt("base-url") // .desc("Sets the base URL of the web service") // .hasArg() // .build()); options.addOption(Option // .builder("u") // .longOpt("username") // .desc("The username for authentication (usually mail address)") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("p") // .longOpt("password") // .desc("The password for authentication") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("c") // .longOpt("command") // .desc(String.format("The command, which should be sent to the device (%s)", commandList)) // .hasArg() // .build()); options.addOption(Option // .builder("q") // .longOpt("query-status") // .desc("Queries the status of the device") // .build()); options.addOption(Option // .builder() // .longOpt("query-calendar") // .desc("Queries the calendar of the device") // .build()); options.addOption(Option // .builder("?") // .longOpt("help") // .desc("Prints this help") // .build()); CommandLineParser parser = new DefaultParser(); CommandLine cmds = null; try { cmds = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); System.exit(1); return; } if (cmds.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); return; } String baseUrl = cmds.getOptionValue("base-url"); String username = cmds.getOptionValue('u'); String password = cmds.getOptionValue('p'); String commandStr = cmds.getOptionValue('c'); boolean doQueryState = cmds.hasOption('q'); boolean doQueryCalendar = cmds.hasOption("query-calendar"); DeviceCommand command = null; if (commandStr != null) { try { command = DeviceCommand.valueOf(commandStr.toUpperCase()); } catch (IllegalArgumentException ex) { System.err.println("Unknown command: " + commandStr); System.exit(1); } } IndegoController controller = new IndegoController(baseUrl, username, password); try { System.out.println("Connecting to device"); controller.connect(); System.out.println(String.format("...Connection established. Device serial number is: %s", controller.getDeviceSerialNumber())); if (command != null) { System.out.println(String.format("Sending command (%s)...", command)); controller.sendCommand(command); System.out.println("...Command sent successfully!"); } if (doQueryState) { System.out.println("Querying device state"); DeviceStateInformation state = controller.getState(); printState(System.out, state); } if (doQueryCalendar) { System.out.println("Querying device calendar"); DeviceCalendar calendar = controller.getCalendar(); printCalendar(System.out, calendar); } } catch (IndegoException ex) { ex.printStackTrace(); System.exit(2); } finally { controller.disconnect(); } }
From source file:com.genentech.chemistry.tool.align.SDFAlign.java
public static void main(String... args) { Options options = new Options(); Option opt = new Option("in", true, "input sd file"); opt.setRequired(true);/*from w w w .j a va 2 s . c om*/ options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("method", true, "fss|sss|MCS|clique (default mcs)."); options.addOption(opt); opt = new Option("ref", true, "reference molecule if not given first in file is used. If multiple ref molecules are read the min RMSD is reported"); options.addOption(opt); opt = new Option("mirror", false, "If given and the molecule is not chiral, return best mirror image."); options.addOption(opt); opt = new Option("rmsdTag", true, "Tagname for output of rmsd, default: no output."); options.addOption(opt); opt = new Option("atomMatch", true, "Sequence of none|default|hcount|noAromatic specifing how atoms are matched cf. oe document.\n" + "noAromatic can be used to make terminal atoms match aliphatic and aromatic atoms.\n" + "Queryfeatures are considered only if default is used."); options.addOption(opt); opt = new Option("bondMatch", true, "Sequence of none|default specifing how bonds are matched cf. oe document."); options.addOption(opt); opt = new Option("keepCoreHydrogens", false, "If not specified the hydrigen atoms are removed from the core."); options.addOption(opt); opt = new Option("outputMol", true, "aligned|original (def: aligned) use original to just compute rmsd."); options.addOption(opt); opt = new Option("doNotOptimize", false, "If specified the RMSD is computed without moving optimizing the overlay."); options.addOption(opt); opt = new Option("quiet", false, "Reduced warining messages"); options.addOption(opt); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { exitWithHelp(e.getMessage(), options); } if (cmd.getArgs().length > 0) exitWithHelp("To many arguments", options); // do not check aromaticity on atoms so that a terminal atom matches aromatic and non aromatic atoms int atomExpr = OEExprOpts.DefaultAtoms; int bondExpr = OEExprOpts.DefaultBonds; String atomMatch = cmd.getOptionValue("atomMatch"); if (atomMatch == null) atomMatch = ""; atomMatch = '|' + atomMatch.toLowerCase() + '|'; String bondMatch = cmd.getOptionValue("bondMatch"); if (bondMatch == null) bondMatch = ""; bondMatch = '|' + bondMatch.toLowerCase() + '|'; String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); String refFile = cmd.getOptionValue("ref"); String method = cmd.getOptionValue("method"); String rmsdTag = cmd.getOptionValue("rmsdTag"); String oMol = cmd.getOptionValue("outputMol"); boolean doMirror = cmd.hasOption("mirror"); boolean doOptimize = !cmd.hasOption("doNotOptimize"); boolean quiet = cmd.hasOption("quiet"); OUTType outputMol = oMol == null ? OUTType.ALIGNED : OUTType.valueOf(oMol.toUpperCase()); if (atomMatch.startsWith("|none")) atomExpr = 0; if (atomMatch.contains("|hcount|")) atomExpr |= OEExprOpts.HCount; if (atomMatch.contains("|noAromatic|")) atomExpr &= (~OEExprOpts.Aromaticity); if (bondMatch.startsWith("|none")) bondExpr = 0; ArrayList<OEMol> refmols = new ArrayList<OEMol>(); if (refFile != null) { oemolistream reffs = new oemolistream(refFile); if (!is3DFormat(reffs.GetFormat())) oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates"); reffs.SetFormat(OEFormat.MDL); int aromodel = OEIFlavor.Generic.OEAroModelOpenEye; int qflavor = reffs.GetFlavor(reffs.GetFormat()); reffs.SetFlavor(reffs.GetFormat(), (qflavor | aromodel)); OEMol rmol = new OEMol(); while (oechem.OEReadMDLQueryFile(reffs, rmol)) { if (!cmd.hasOption("keepCoreHydrogens")) oechem.OESuppressHydrogens(rmol); refmols.add(rmol); rmol = new OEMol(); } rmol.delete(); if (refmols.size() == 0) throw new Error("reference file had no entries"); reffs.close(); } oemolistream fitfs = new oemolistream(inFile); if (!is3DFormat(fitfs.GetFormat())) oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates"); oemolostream ofs = new oemolostream(outFile); if (!is3DFormat(ofs.GetFormat())) oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates"); AlignInterface aligner = null; OEGraphMol fitmol = new OEGraphMol(); if (oechem.OEReadMolecule(fitfs, fitmol)) { if (refmols.size() == 0) { OEMol rmol = new OEMol(fitmol); if (!cmd.hasOption("keepCoreHydrogens")) oechem.OESuppressHydrogens(rmol); refmols.add(rmol); } if ("sss".equalsIgnoreCase(method)) { aligner = new SSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr, quiet); } else if ("clique".equalsIgnoreCase(method)) { aligner = new CliqueAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr, quiet); } else if ("fss".equalsIgnoreCase(method)) { if (cmd.hasOption("atomMatch") || cmd.hasOption("bondMatch")) exitWithHelp("method fss does not support '-atomMatch' or '-bondMatch'", options); aligner = new FSSAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror); } else { aligner = new McsAlign(refmols, outputMol, rmsdTag, doOptimize, doMirror, atomExpr, bondExpr, quiet); } do { aligner.align(fitmol); oechem.OEWriteMolecule(ofs, fitmol); } while (oechem.OEReadMolecule(fitfs, fitmol)); } fitmol.delete(); if (aligner != null) aligner.close(); for (OEMolBase mol : refmols) mol.delete(); fitfs.close(); ofs.close(); }
From source file:com.gtwm.jasperexecute.RunJasperReports.java
public static void main(String[] args) throws Exception { RunJasperReports runJasperReports = new RunJasperReports(); // Set up command line parser Options options = new Options(); Option reports = OptionBuilder.withArgName("reportlist").hasArg() .withDescription("Comma separated list of JasperReport XML input files").create("reports"); options.addOption(reports);/* ww w. ja v a 2 s .c o m*/ Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg() .withDescription("Email address to send generated reports to").create("emailto"); options.addOption(emailTo); Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg() .withDescription("Sender email address").create("emailfrom"); options.addOption(emailFrom); Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg() .withDescription("Subject line of email").create("emailsubject"); options.addOption(emailSubjectLine); Option emailHostOption = OptionBuilder.withArgName("emailhost").hasArg() .withDescription("Address of email server").create("emailhost"); options.addOption(emailHostOption); Option emailUsernameOption = OptionBuilder.withArgName("emailuser").hasArg() .withDescription("Username if email server requires authentication").create("emailuser"); options.addOption(emailUsernameOption); Option emailPasswordOption = OptionBuilder.withArgName("emailpass").hasArg() .withDescription("Password if email server requires authentication").create("emailpass"); options.addOption(emailPasswordOption); Option outputFolder = OptionBuilder.withArgName("foldername").hasArg() .withDescription( "Folder to write generated reports to, with trailing separator (slash or backslash)") .create("folder"); options.addOption(outputFolder); Option dbTypeOption = OptionBuilder.withArgName("databasetype").hasArg() .withDescription("Currently supported types are: " + Arrays.asList(DatabaseType.values())) .create("dbtype"); options.addOption(dbTypeOption); Option dbNameOption = OptionBuilder.withArgName("databasename").hasArg() .withDescription("Name of the database to run reports against").create("dbname"); options.addOption(dbNameOption); Option dbUserOption = OptionBuilder.withArgName("username").hasArg() .withDescription("Username to connect to databasewith").create("dbuser"); options.addOption(dbUserOption); Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password") .create("dbpass"); options.addOption(dbPassOption); Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg() .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output"); options.addOption(outputTypeOption); Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg() .withDescription("Output filename (excluding filetype suffix)").create("filename"); options.addOption(outputFilenameOption); Option dbHostOption = OptionBuilder.withArgName("host").hasArg().withDescription("Database host address") .create("dbhost"); options.addOption(dbHostOption); Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription( "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85") .create("params"); options.addOption(paramsOption); // Parse command line CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports"); if (reportsDefinitionFileNamesCvs == null) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar RunJasperReports.jar", options); System.out.println(); System.out.println("See www.agilebase.co.uk/opensource for further documentation"); System.out.println(); throw new IllegalArgumentException("No reports specified"); } String outputPath = commandLine.getOptionValue("folder"); List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(",")); List<String> outputFileNames = new ArrayList<String>(); DatabaseType databaseType = DatabaseType.POSTGRESQL; String databaseTypeString = commandLine.getOptionValue("dbtype"); if (databaseTypeString != null) { databaseType = DatabaseType.valueOf(commandLine.getOptionValue("dbtype").toUpperCase()); } String databaseName = commandLine.getOptionValue("dbname"); String databaseUsername = commandLine.getOptionValue("dbuser"); String databasePassword = commandLine.getOptionValue("dbpass"); String databaseHost = commandLine.getOptionValue("dbhost"); if (databaseHost == null) { databaseHost = "localhost"; } OutputType outputType = OutputType.PDF; String outputTypeString = commandLine.getOptionValue("output"); if (outputTypeString != null) { outputType = OutputType.valueOf(outputTypeString.toUpperCase()); } String parametersString = commandLine.getOptionValue("params"); Map parameters = runJasperReports.prepareParameters(parametersString); String outputFilenameSpecified = commandLine.getOptionValue("filename"); if (outputFilenameSpecified == null) { outputFilenameSpecified = ""; } // Iterate over reports, generating output for each for (String reportsDefinitionFileName : reportDefinitionFileNames) { String outputFilename = null; if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) { outputFilename = outputFilenameSpecified; } else { outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", ""); outputFilename = outputFilename.replaceAll("^.*\\/", ""); outputFilename = outputFilename.replaceAll("^.*\\\\", ""); } outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "." + outputType.toString().toLowerCase(); if (outputPath != null) { if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) { outputPath += java.io.File.separator; } outputFilename = outputPath + outputFilename; } System.out.println("Going to generate report " + outputFilename); if (outputType.equals(OutputType.PDF)) { runJasperReports.generatePdfReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } else if (outputType.equals(OutputType.TEXT)) { runJasperReports.generateTextReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } else if (outputType.equals(OutputType.CSV)) { runJasperReports.generateCSVReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } else if (outputType.equals(OutputType.XLS)) { // NB: parameters are in a different order for XLS for some reasons runJasperReports.generateJxlsReport(reportsDefinitionFileName, outputFilename, databaseType, databaseHost, databaseName, databaseUsername, databasePassword, parameters); } else { runJasperReports.generateHtmlReport(reportsDefinitionFileName, outputFilename, databaseType, databaseName, databaseUsername, databasePassword, databaseHost, parameters); } outputFileNames.add(outputFilename); } String emailRecipientList = commandLine.getOptionValue("emailto"); if (emailRecipientList != null) { Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(","))); String emailSender = commandLine.getOptionValue("emailfrom"); String emailSubject = commandLine.getOptionValue("emailsubject"); if (emailSubject == null) { emailSubject = "Report attached"; } String emailHost = commandLine.getOptionValue("emailhost"); if (emailHost == null) { emailHost = "localhost"; } String emailUser = commandLine.getOptionValue("emailuser"); String emailPass = commandLine.getOptionValue("emailpass"); System.out.println("Emailing reports to " + emailRecipients); runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender, emailSubject, outputFileNames); } else { System.out.println("Email not generated (no recipients specified)"); } }
From source file:com.ilopez.jasperemail.JasperEmail.java
public static void main(String[] args) throws Exception { JasperEmail runJasperReports = new JasperEmail(); // Set up command line parser Options options = new Options(); Option reports = OptionBuilder.withArgName("reportlist").hasArg() .withDescription("Comma separated list of JasperReport XML input files").create("reports"); options.addOption(reports);//from w ww .j a va 2s. c om Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg() .withDescription("Email address to send generated reports to").create("emailto"); options.addOption(emailTo); Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg() .withDescription("Sender email address").create("emailfrom"); options.addOption(emailFrom); Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg() .withDescription("Subject line of email").create("emailsubject"); options.addOption(emailSubjectLine); Option smtpHostOption = OptionBuilder.withArgName("smtphost").hasArg() .withDescription("Address of email server").create("smtphost"); options.addOption(smtpHostOption); Option smtpUserOption = OptionBuilder.withArgName("smtpuser").hasArg() .withDescription("Username if email server requires authentication").create("smtpuser"); options.addOption(smtpUserOption); Option smtpPassOption = OptionBuilder.withArgName("smtppass").hasArg() .withDescription("Password if email server requires authentication").create("smtppass"); options.addOption(smtpPassOption); Option smtpAuthOption = OptionBuilder.withArgName("smtpauth").hasArg() .withDescription("Set SMTP Authentication").create("smtpauth"); options.addOption(smtpAuthOption); Option smtpPortOption = OptionBuilder.withArgName("smtpport").hasArg() .withDescription("Port for the SMTP server 25/468/587/2525/2526").create("smtpport"); options.addOption(smtpPortOption); Option smtpTypeOption = OptionBuilder.withArgName("smtptype").hasArg() .withDescription("Define SMTP Type, one of: " + Arrays.asList(OptionValues.SMTPType.values())) .create("smtptype"); options.addOption(smtpTypeOption); Option outputFolder = OptionBuilder.withArgName("foldername").hasArg() .withDescription( "Folder to write generated reports to, with trailing separator (slash or backslash)") .create("folder"); options.addOption(outputFolder); Option dbJDBCClass = OptionBuilder.withArgName("jdbcclass").hasArg() .withDescription("Provide the JDBC Database Class ").create("jdbcclass"); options.addOption(dbJDBCClass); Option dbJDBCURL = OptionBuilder.withArgName("jdbcurl").hasArg() .withDescription("Provide the JDBC Database URL").create("jdbcurl"); options.addOption(dbJDBCURL); Option dbUserOption = OptionBuilder.withArgName("username").hasArg() .withDescription("Username to connect to databasewith").create("dbuser"); options.addOption(dbUserOption); Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password") .create("dbpass"); options.addOption(dbPassOption); Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg() .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output"); options.addOption(outputTypeOption); Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg() .withDescription("Output filename (excluding filetype suffix)").create("filename"); options.addOption(outputFilenameOption); Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription( "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85") .create("params"); options.addOption(paramsOption); // Parse command line CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports"); if (reportsDefinitionFileNamesCvs == null) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar JasperEmail.jar", options); System.out.println(); System.out.println("See http://github.com/ilopez/JasperEmail for further documentation"); System.out.println(); throw new IllegalArgumentException("No reports specified"); } String outputPath = commandLine.getOptionValue("folder"); List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(",")); List<String> outputFileNames = new ArrayList<String>(); String jdbcClass = commandLine.getOptionValue("jdbcclass"); String jdbcURL = commandLine.getOptionValue("jdbcurl"); String databaseUsername = commandLine.getOptionValue("dbuser"); String databasePassword = commandLine.getOptionValue("dbpass"); OutputType outputType = OutputType.PDF; String outputTypeString = commandLine.getOptionValue("output"); if (outputTypeString != null) { outputType = OutputType.valueOf(outputTypeString.toUpperCase()); } String parametersString = commandLine.getOptionValue("params"); Map parameters = runJasperReports.prepareParameters(parametersString); String outputFilenameSpecified = commandLine.getOptionValue("filename"); if (outputFilenameSpecified == null) { outputFilenameSpecified = ""; } // SMTP PORT Integer smtpport = Integer.parseInt(commandLine.getOptionValue("smtpport")); Boolean smtpauth = Boolean.parseBoolean(commandLine.getOptionValue("smtpauth")); OptionValues.SMTPType smtptype; String smtptypestring = commandLine.getOptionValue("smtpenc"); if (smtptypestring != null) { smtptype = OptionValues.SMTPType.valueOf(smtptypestring.toUpperCase()); } else { smtptype = OptionValues.SMTPType.PLAIN; } // SMTP TLS // SMTP // Iterate over reports, generating output for each for (String reportsDefinitionFileName : reportDefinitionFileNames) { String outputFilename = null; if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) { outputFilename = outputFilenameSpecified; } else { outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", ""); outputFilename = outputFilename.replaceAll("^.*\\/", ""); outputFilename = outputFilename.replaceAll("^.*\\\\", ""); } outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "." + outputType.toString().toLowerCase(); if (outputPath != null) { if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) { outputPath += java.io.File.separator; } outputFilename = outputPath + outputFilename; } System.out.println("Going to generate report " + outputFilename); runJasperReports.generateReport(reportsDefinitionFileName, jdbcClass, jdbcURL, databaseUsername, databasePassword, jdbcURL, parameters); outputFileNames.add(outputFilename); } String emailRecipientList = commandLine.getOptionValue("emailto"); if (emailRecipientList != null) { Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(","))); String emailSender = commandLine.getOptionValue("emailfrom"); String emailSubject = commandLine.getOptionValue("emailsubject"); if (emailSubject == null) { emailSubject = "Report attached"; } String emailHost = commandLine.getOptionValue("smtphost"); if (emailHost == null) { emailHost = "localhost"; } String emailUser = commandLine.getOptionValue("smtpuser"); String emailPass = commandLine.getOptionValue("smtppass"); System.out.println("Emailing reports to " + emailRecipients); runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender, emailSubject, outputFileNames, smtpauth, smtptype, smtpport); } else { System.out.println("Email not generated (no recipients specified)"); } }