List of usage examples for java.lang NumberFormatException getMessage
public String getMessage()
From source file:at.ac.tuwien.inso.subcat.postprocessor.PostProcessor.java
public static void main(String[] args) { Map<String, PostProcessorTask> steps = new HashMap<String, PostProcessorTask>(); PostProcessorTask _step = new ClassificationTask(); steps.put(_step.getName(), _step);/*from w ww . j a v a 2 s. co m*/ CommentAnalyserTask commentAnalysisStep = new CommentAnalyserTask(); steps.put(commentAnalysisStep.getName(), commentAnalysisStep); AccountInterlinkingTask interlinkingTask = new AccountInterlinkingTask(); steps.put(interlinkingTask.getName(), interlinkingTask); _step = new CommitBugInterlinkingTask(); steps.put(_step.getName(), _step); Options options = new Options(); options.addOption("h", "help", false, "Show this options"); options.addOption("d", "db", true, "The database to process (required)"); options.addOption("v", "verbose", false, "Show details"); options.addOption("p", "project", true, "The project ID to process"); options.addOption("P", "list-projects", false, "List all registered projects"); options.addOption("S", "list-processor-steps", false, "List all registered processor steps"); options.addOption("s", "processor-step", true, "A processor step name"); options.addOption("c", "commit-dictionary", true, "Path to a classification dictionary for commit message classification"); options.addOption("b", "bug-dictionary", true, "Path to a classification dictionary for bug classification"); options.addOption("m", "smart-matching", true, "Smart user matching configuration. Syntax: <method>:<distance>"); options.addOption("M", "list-matching-methods", false, "List smart matching methods"); final Reporter reporter = new Reporter(true); reporter.startTimer(); Settings settings = new Settings(); ModelPool pool = null; boolean printTraces = false; CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); printTraces = cmd.hasOption("verbose"); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("postprocessor", options); return; } if (cmd.hasOption("list-processor-steps")) { for (String proj : steps.keySet()) { System.out.println(" " + proj); } return; } if (cmd.hasOption("list-matching-methods")) { for (String method : HashFunc.getHashFuncNames()) { System.out.println(" " + method); } return; } if (cmd.hasOption("db") == false) { reporter.error("post-processor", "Option --db is required"); reporter.printSummary(); return; } File dbf = new File(cmd.getOptionValue("db")); if (dbf.exists() == false || dbf.isFile() == false) { reporter.error("post-processor", "Invalid database file path"); reporter.printSummary(); return; } pool = new ModelPool(cmd.getOptionValue("db"), 2); if (cmd.hasOption("list-projects")) { Model model = pool.getModel(); for (Project proj : model.getProjects()) { System.out.println(" " + proj.getId() + ": " + proj.getDate()); } model.close(); return; } Integer projId = null; if (cmd.hasOption("project") == false) { reporter.error("post-processor", "Option --project is required"); reporter.printSummary(); return; } else { try { projId = Integer.parseInt(cmd.getOptionValue("project")); } catch (NumberFormatException e) { reporter.error("post-processor", "Invalid project ID"); reporter.printSummary(); return; } } Model model = pool.getModel(); Project project = model.getProject(projId); model.close(); if (project == null) { reporter.error("post-processor", "Invalid project ID"); reporter.printSummary(); return; } if (cmd.hasOption("bug-dictionary")) { DictionaryParser dp = new DictionaryParser(); for (String path : cmd.getOptionValues("bug-dictionary")) { try { Dictionary dict = dp.parseFile(path); settings.bugDictionaries.add(dict); } catch (FileNotFoundException e) { reporter.error("post-processor", "File not found: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } catch (XmlReaderException e) { reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } } } if (cmd.hasOption("commit-dictionary")) { DictionaryParser dp = new DictionaryParser(); for (String path : cmd.getOptionValues("commit-dictionary")) { try { Dictionary dict = dp.parseFile(path); settings.srcDictionaries.add(dict); } catch (FileNotFoundException e) { reporter.error("post-processor", "File not found: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } catch (XmlReaderException e) { reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } } } if (cmd.hasOption("smart-matching")) { String str = cmd.getOptionValue("smart-matching"); String[] parts = str.split(":"); if (parts.length != 2) { reporter.error("post-processor", "Unexpected smart-matching format"); reporter.printSummary(); return; } HashFunc func = HashFunc.getHashFunc(parts[0]); if (func == null) { reporter.error("post-processor", "Unknown smart matching hash function"); reporter.printSummary(); return; } int dist = -1; try { dist = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { dist = -1; } if (dist < 0) { reporter.error("post-processor", "Invalid smart matching edist distance"); reporter.printSummary(); return; } interlinkingTask.setDistance(dist); interlinkingTask.setHashFunc(func); } PostProcessor processor = new PostProcessor(project, pool, settings); if (cmd.hasOption("processor-step")) { for (String stepName : cmd.getOptionValues("processor-step")) { PostProcessorTask step = steps.get(stepName); if (step == null) { reporter.error("post-processor", "Unknown processor step: '" + stepName + "'"); reporter.printSummary(); return; } processor.register(step); } } else { processor.register(steps.values()); } if (printTraces == true) { model = pool.getModel(); final Stats stats = model.getStats(project); model.close(); processor.addListener(new PostProcessorListener() { private int commitCount = 0; private int bugCount = 0; @Override public void commit(PostProcessor proc) { commitCount++; reporter.note("post-processor", "status: Commit " + commitCount + "/" + stats.commitCount); } @Override public void bug(PostProcessor proc) { bugCount++; reporter.note("post-processor", "status: Bug " + bugCount + "/" + stats.bugCount); } }); } processor.process(); } catch (ParseException e) { reporter.error("post-processor", "Parsing failed: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (ClassNotFoundException e) { reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (SQLException e) { reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (PostProcessorException e) { reporter.error("post-processor", "Post-Processor Error: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } finally { if (pool != null) { pool.close(); } } reporter.printSummary(true); }
From source file:net.cliftonsnyder.svgchart.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")"); options.addOption("h", "height", true, "chart height"); options.addOption("i", "input-file", true, "input file [default: stdin]"); options.addOption("o", "output-file", true, "output file [default: stdout]"); options.addOption("w", "width", true, "chart width"); options.addOption("?", "help", false, "print a brief help message"); Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES)); type.setRequired(true);/*ww w. java 2 s . c o m*/ options.addOption(type); CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); if (line.hasOption("help")) { formatter.printHelp(USAGE, options); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong System.err.println("unable to parse command line: " + exp.getMessage()); formatter.printHelp(USAGE, options); System.exit(1); } SVGChart chart = null; String tmp = line.getOptionValue("type"); Matcher m = null; for (Pattern p : SVGChart.TYPE_PATTERNS) { if ((m = p.matcher(tmp)).matches()) { switch (m.group().charAt(0)) { case 'l': // DEBUG System.err.println("line"); break; case 'b': System.err.println("bar"); chart = new BarChart(); break; case 'p': System.err.println("pie"); break; default: System.err.println("unknown or unimplemented chart type: '" + tmp + "'"); System.exit(1); } } } try { chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH))); } catch (NumberFormatException e) { System.err.println( "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'"); System.exit(1); } try { chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT))); } catch (NumberFormatException e) { System.err.println( "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'"); System.exit(1); } InputStream in = System.in; tmp = line.getOptionValue("input-file", "-"); if ("-".equals(tmp)) { in = System.in; } else { try { in = new FileInputStream(tmp); } catch (FileNotFoundException e) { System.err.println("input file not found: '" + tmp + "'"); System.exit(1); } } PrintStream out = System.out; tmp = line.getOptionValue("output-file", "-"); if ("-".equals(tmp)) { out = System.out; } else { try { out = new PrintStream(new FileOutputStream(tmp)); } catch (FileNotFoundException e) { System.err.println("output file not found: '" + tmp + "'"); System.exit(1); } } tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET); chart.setStyleSheet(tmp); try { chart.parseInput(in); } catch (IOException e) { System.err.println("I/O error while reading input"); System.exit(1); } catch (net.cliftonsnyder.svgchart.parse.ParseException e) { System.err.println("error parsing input: " + e.getMessage()); } chart.createChart(); try { chart.printChart(out, true); } catch (IOException e) { System.err.println("error serializing output"); System.exit(1); } }
From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java
public static void main(String args[]) { // Example Command line args //-n 10000 -g w12ags104a.jennings.home -i 5565 -m https://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0 -f D:\github\performance-test-harness-for-geoevent\app\simulations\faa-stream.csv -r 1000,3000,1000 int numberEvents = 10000; // Number of Events String gisServer = "w12ags104a.jennings.home"; // GIS Server int inputTcpPort = 5565; // TCP Input Port String msLayerUrl = "http://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0"; String EventsInputFile = "D:\\github\\performance-test-harness-for-geoevent\\app\\simulations\\faa-stream.csv"; // Events input File int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("g", true, "GIS Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("m", true, "Map Service Layer URL"); opts.addOption("f", true, "File with GeoEvents to Send"); opts.addOption("r", true, "Rates to test Start,End,Step"); opts.addOption("h", false, "Help"); try {// w w w. j a v a 2 s . c om CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (org.apache.commons.cli.ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new org.apache.commons.cli.ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("g")) { gisServer = cmd.getOptionValue("g"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { inputTcpPort = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("m")) { msLayerUrl = cmd.getOptionValue("m"); } if (cmd.hasOption("f")) { EventsInputFile = cmd.getOptionValue("f"); } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new org.apache.commons.cli.ParseException( "Rate must be three comma seperated values or a single value"); } } catch (org.apache.commons.cli.ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new org.apache.commons.cli.ParseException(cmdInputErrorMsg); } // Assuming the ES port is 9220 RunTcpInBdsOutTest t = new RunTcpInBdsOutTest(); DecimalFormat df = new DecimalFormat("##0"); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); Thread.sleep(3 * 1000); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumberOfEvents -g GISServer -i InputTCPPort -m MapServerLayerURL -f FileWithEvents -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java
public static void main(String args[]) { int numberEvents = 10000; //int brake = 1000; String server = "ags104"; int in_port = 5565; int out_port = 5575; int start_rate = 5000; int end_rate = 5005; int rate_step = 1; Options opts = new Options(); opts.addOption("n", true, "Number of Events"); opts.addOption("s", true, "Server"); opts.addOption("i", true, "Input TCP Port"); opts.addOption("o", true, "Output TCP Port"); opts.addOption("r", true, "Range"); opts.addOption("h", false, "Help"); try {/*from ww w . ja v a2 s. c o m*/ CommandLineParser parser = new BasicParser(); CommandLine cmd = null; try { cmd = parser.parse(opts, args, false); } catch (ParseException ignore) { System.err.println(ignore.getMessage()); } String cmdInputErrorMsg = ""; if (cmd.getOptions().length == 0 || cmd.hasOption("h")) { throw new ParseException("Show Help"); } if (cmd.hasOption("n")) { String val = cmd.getOptionValue("n"); try { numberEvents = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for n. Must be integer.\n"; } } if (cmd.hasOption("s")) { server = cmd.getOptionValue("s"); } if (cmd.hasOption("i")) { String val = cmd.getOptionValue("i"); try { in_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for i. Must be integer.\n"; } } if (cmd.hasOption("o")) { String val = cmd.getOptionValue("o"); try { out_port = Integer.valueOf(val); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for o. Must be integer.\n"; } } if (cmd.hasOption("r")) { String val = cmd.getOptionValue("r"); try { String parts[] = val.split(","); if (parts.length == 3) { start_rate = Integer.parseInt(parts[0]); end_rate = Integer.parseInt(parts[1]); rate_step = Integer.parseInt(parts[2]); } else if (parts.length == 1) { // Run single rate start_rate = Integer.parseInt(parts[0]); end_rate = start_rate; rate_step = start_rate; } else { throw new ParseException("Rate must be three comma seperated values or a single value"); } } catch (ParseException e) { cmdInputErrorMsg += e.getMessage(); } catch (NumberFormatException e) { cmdInputErrorMsg += "Invalid value for r. Must be integers.\n"; } } if (!cmdInputErrorMsg.equalsIgnoreCase("")) { throw new ParseException(cmdInputErrorMsg); } DecimalFormat df = new DecimalFormat("##0"); RunTcpInTcpOutTest t = new RunTcpInTcpOutTest(); if (start_rate == end_rate) { // Single Rate Test System.out.println("*********************************"); System.out.println("Incremental testing at requested rate: " + start_rate); System.out.println("Count,Incremental Rate"); t.runTest(numberEvents, start_rate, server, in_port, out_port, true); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println("Overall Average Send Rate, Received Rate"); System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } else { System.out.println("*********************************"); System.out.println("rateRqstd,avgSendRate,avgRcvdRate"); //for (int rate: rates) { for (int rate = start_rate; rate <= end_rate; rate += rate_step) { t.runTest(numberEvents, rate, server, in_port, out_port, false); if (t.send_rate < 0 || t.rcv_rate < 0) { throw new Exception("Test Run Failed!"); } System.out.println( Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate)); } } } catch (ParseException e) { System.out.println("Invalid Command Options: "); System.out.println(e.getMessage()); System.out.println( "Command line options: -n NumEvents -s Server -i InputPort -o OutputPort -r StartRate,EndRate,Step"); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.github.andreax79.meca.Main.java
@SuppressWarnings("static-access") public static void main(String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption("X", "suppress-output", false, "don't create the output file"); OptionGroup boundariesOptions = new OptionGroup(); boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)")); boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries")); boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries")); boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries")); options.addOptionGroup(boundariesOptions); OptionGroup colorOptions = new OptionGroup(); colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)")); colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme")); colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme")); options.addOptionGroup(colorOptions); options.addOption(OptionBuilder.withLongOpt("rule").withDescription("rule number (required)").hasArg() .withArgName("rule").create()); options.addOption(OptionBuilder.withLongOpt("width").withDescription("space width (required)").hasArg() .withArgName("width").create()); options.addOption(OptionBuilder.withLongOpt("steps").withDescription("number of steps (required)").hasArg() .withArgName("steps").create()); options.addOption(OptionBuilder.withLongOpt("alpha").withDescription("memory factor (default 0)").hasArg() .withArgName("alpha").create()); options.addOption(OptionBuilder.withLongOpt("pattern").withDescription("inititial pattern").hasArg() .withArgName("pattern").create()); options.addOption("s", "single-seed", false, "single cell seed"); options.addOption("si", "single-seed-inverse", false, "all 1 except one cell"); options.addOption(OptionBuilder.withLongOpt("update-patter") .withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")").hasArg() .withArgName("updatepatter").create()); // test//w w w. ja v a 2 s .com // args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (!line.hasOption("rule")) throw new ParseException("no rule number (use --rule=XX)"); int rule; try { rule = Integer.parseInt(line.getOptionValue("rule")); if (rule < 0 || rule > 15) throw new ParseException("invalid rule number"); } catch (NumberFormatException ex) { throw new ParseException("invalid rule number"); } if (!line.hasOption("width")) throw new ParseException("no space width (use --width=XX)"); int width; try { width = Integer.parseInt(line.getOptionValue("width")); if (width < 1) throw new ParseException("invalid width"); } catch (NumberFormatException ex) { throw new ParseException("invalid width"); } if (!line.hasOption("steps")) throw new ParseException("no number of steps (use --steps=XX)"); int steps; try { steps = Integer.parseInt(line.getOptionValue("steps")); if (width < 1) throw new ParseException("invalid number of steps"); } catch (NumberFormatException ex) { throw new ParseException("invalid number of steps"); } double alpha = 0; if (line.hasOption("alpha")) { try { alpha = Double.parseDouble(line.getOptionValue("alpha")); if (alpha < 0 || alpha > 1) throw new ParseException("invalid alpha"); } catch (NumberFormatException ex) { throw new ParseException("invalid alpha"); } } String pattern = null; if (line.hasOption("pattern")) { pattern = line.getOptionValue("pattern"); if (pattern != null) pattern = pattern.trim(); } if (line.hasOption("single-seed")) pattern = "S"; else if (line.hasOption("single-seed-inverse")) pattern = "SI"; UpdatePattern updatePatter = UpdatePattern.synchronous; if (line.hasOption("update-patter")) { try { updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter")); } catch (IllegalArgumentException ex) { throw new ParseException(ex.getMessage()); } } Boundaries boundaries = Boundaries.periodic; if (line.hasOption("periodic")) boundaries = Boundaries.periodic; else if (line.hasOption("fixed")) boundaries = Boundaries.fixed; else if (line.hasOption("adiabatic")) boundaries = Boundaries.adiabatic; else if (line.hasOption("reflective")) boundaries = Boundaries.reflective; ColorScheme colorScheme = ColorScheme.noColor; if (line.hasOption("black-white")) colorScheme = ColorScheme.noColor; else if (line.hasOption("activation-color")) colorScheme = ColorScheme.activationColor; else if (line.hasOption("omega-color")) colorScheme = ColorScheme.omegaColor; Output output = Output.all; if (line.hasOption("suppress-output")) output = Output.noOutput; Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme); } catch (ParseException ex) { System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>"); System.err.println(); System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata"); System.err.println(); System.err.println("This program is free software; you can redistribute it and/or modify it"); System.err.println("under the terms of the GNU General Public License as published by the"); System.err.println("Free Software Foundation; either version 2 of the License, or (at your"); System.err.println("option) any later version."); System.err.println(); System.err.println("This program is distributed in the hope that it will be useful, but"); System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY"); System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License"); System.err.println("for more details."); System.err.println(); System.err.println("You should have received a copy of the GNU General Public License along"); System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,"); System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)"); System.err.println(); System.err.println(ex.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("main", options); } catch (IOException ex) { System.err.println("IO exception:" + ex.getMessage()); } }
From source file:edu.msu.cme.rdp.multicompare.Main.java
public static void main(String[] args) throws Exception { PrintStream hier_out = null;/*from ww w .java 2s . co m*/ PrintWriter assign_out = new PrintWriter(new NullWriter()); PrintStream bootstrap_out = null; File hier_out_filename = null; String propFile = null; File biomFile = null; File metadataFile = null; PrintWriter shortseq_out = null; List<MCSample> samples = new ArrayList(); ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; float conf = CmdOptions.DEFAULT_CONF; String gene = null; int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } else { throw new IllegalArgumentException("Require the output file for classification assignment"); } if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT)); hier_out = new PrintStream(hier_out_filename); } if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) { biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) { metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT)); } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("biom")) { format = ClassificationResultFormatter.FORMAT.biom; } else { throw new IllegalArgumentException( "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (propFile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " not found, choose from" + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + ", " + ClassifierFactory.FUNGALITS_unite_GENE); } } if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) { min_bootstrap_words = Integer .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)); if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) { throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS); } } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT); try { conf = Float.valueOf(confString); } catch (NumberFormatException e) { throw new IllegalArgumentException("Confidence must be a decimal number"); } if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) { shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) { bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)); } if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) { throw new IllegalArgumentException("biom format requires an input biom file"); } if (biomFile != null) { // if input biom file provided, use biom format format = ClassificationResultFormatter.FORMAT.biom; } args = line.getArgs(); for (String arg : args) { String[] inFileNames = arg.split(","); File inputFile = new File(inFileNames[0]); File idmappingFile = null; if (!inputFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\""); } if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\""); } } MCSample nextSample = new MCSample(inputFile, idmappingFile); samples.add(nextSample); } if (propFile == null && gene == null) { gene = CmdOptions.DEFAULT_GENE; } if (samples.size() < 1) { throw new IllegalArgumentException("Require at least one sample files"); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, ""); return; } MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile); MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format, min_bootstrap_words); assign_out.close(); if (hier_out != null) { DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples); result.getRoot().topDownVisit(printVisitor); hier_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(hier_out_filename.getParentFile(), "cnadjusted_" + hier_out_filename.getName()); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } } if (bootstrap_out != null) { for (MCSample sample : samples) { MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample); } bootstrap_out.close(); } if (shortseq_out != null) { for (String id : result.getBadSequences()) { shortseq_out.write(id + "\n"); } shortseq_out.close(); } }
From source file:me.camerongray.teamlocker.server.Server.java
public static void main(String[] args) throws PropertyVetoException, SQLException { ConnectionManager.initialise("localhost", "teamlocker", "teamlocker", "teamlocker"); before((request, response) -> {//from w ww .j av a2s.c o m // Log request StringBuilder sb = new StringBuilder(); sb.append(request.requestMethod()); sb.append(" " + request.url()); sb.append(" " + request.body()); System.out.println(sb); if (request.headers("Authorization") == null) { response.header("WWW-Authenticate", "Basic"); halt(401); } RequestCredentials credentials = new RequestCredentials(request); if (!Auth.checkCredentials(credentials.username, credentials.password)) { ResponseBuilder.errorHalt(response, 401, "Incorrect username/password"); } }); get("/check_auth/", (request, response) -> { return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/users/:userId/", (request, response) -> { DynaBean user = null; try (Database database = new Database(ConnectionManager.getConnection(request))) { if (request.params(":userId").equals("self")) { try { user = database.getUser((new RequestCredentials(request)).getUsername()); } catch (ObjectNotFoundException e) { ResponseBuilder.errorHalt(response, 404, "User not found"); } } else { Auth.enforceAdmin(request, response); try { user = database.getUser(Integer.parseInt(request.params(":userId"))); } catch (NumberFormatException e) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } catch (ObjectNotFoundException e) { ResponseBuilder.errorHalt(response, 404, "User not found"); } } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("user", ResponseBuilder.objectOf("id", (int) user.get("id"), "full_name", (String) user.get("full_name"), "username", (String) user.get("username"), "email", (String) user.get("email"), "auth_hash", (String) user.get("auth_hash"), "encrypted_private_key", (String) user.get("encrypted_private_key"), "public_key", (String) user.get("public_key"), "admin", (boolean) user.get("admin"), "pbkdf2_salt", (String) user.get("pbkdf2_salt"), "aes_iv", (String) user.get("aes_iv")))); }); get("/users/:userId/encrypted_aes_keys/", (request, response) -> { int userId; if (request.params(":userId").equals("self")) { userId = Auth.getCurrentUserId(request); } else { Auth.enforceAdmin(request, response); userId = Integer.parseInt(request.params(":userId")); } List<DynaBean> accountData; try (Database database = new Database(ConnectionManager.getConnection(request))) { accountData = database.getUserAccountData(userId); } ArrayList<JSONObject> aesKeyObjects = new ArrayList<>(); for (DynaBean accountDataItem : accountData) { aesKeyObjects.add(ResponseBuilder.objectOf("account_id", (int) accountDataItem.get("account_id"), "encrypted_aes_key", (String) accountDataItem.get("encrypted_aes_key"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("encrypted_aes_keys", ResponseBuilder.fromArrayList(aesKeyObjects))); }); get("/users/:userId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); List<DynaBean> permissions = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { permissions = database.getUserPermissions(Integer.parseInt(request.params(":userId"))); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } } ArrayList<JSONObject> responseObjects = new ArrayList<>(); for (DynaBean permission : permissions) { responseObjects.add(ResponseBuilder.objectOf("folder_id", (int) permission.get("folder_id"), "read", (boolean) permission.get("read"), "write", (boolean) permission.get("write"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("permissions", ResponseBuilder.fromArrayList(responseObjects))); }); delete("/users/:userId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.deleteUserPermissions(Integer.parseInt(request.params(":userId"))); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/users/:userId/", (request, response) -> { Auth.enforceAdmin(request, response); int userId = -1; try { userId = Integer.parseInt(request.params(":userId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "User ID must be a number"); } JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postUsers"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } try (Database database = new Database(ConnectionManager.getConnection(request))) { boolean usernameExists = true; try { DynaBean user = database.getUser(requestJson.getString("username")); if ((Integer) user.get("id") == userId) { usernameExists = false; } } catch (ObjectNotFoundException ex) { usernameExists = false; } if (usernameExists) { ResponseBuilder.errorHalt(response, 409, "A user with that username already exists"); } database.updateUser(userId, requestJson.getString("username"), requestJson.getString("full_name"), requestJson.getString("email"), requestJson.getBoolean("admin")); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/users/", (request, response) -> { Auth.enforceAdmin(request, response); ArrayList<JSONObject> userObjects = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { List<DynaBean> users = database.getAllUsers(); for (DynaBean user : users) { userObjects.add(ResponseBuilder.objectOf("id", (int) user.get("id"), "full_name", (String) user.get("full_name"), "username", (String) user.get("username"), "email", (String) user.get("email"), "auth_hash", (String) user.get("auth_hash"), "encrypted_private_key", (String) user.get("encrypted_private_key"), "public_key", (String) user.get("public_key"), "admin", (boolean) user.get("admin"), "pbkdf2_salt", (String) user.get("pbkdf2_salt"), "aes_iv", (String) user.get("aes_iv"))); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("users", ResponseBuilder.fromArrayList(userObjects))); }); put("/users/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "putUsers"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } int userId = -1; try (Database database = new Database(ConnectionManager.getConnection(request))) { boolean userExists = true; try { database.getUser(requestJson.getString("username")); } catch (ObjectNotFoundException ex) { userExists = false; } if (userExists) { ResponseBuilder.errorHalt(response, 409, "A user with that username already exists"); } userId = database.addUser(requestJson.getString("full_name"), requestJson.getString("username"), requestJson.getString("email"), BCrypt.hashpw(requestJson.getString("auth_key"), BCrypt.gensalt()), requestJson.getString("encrypted_private_key"), requestJson.getString("public_key"), requestJson.getBoolean("admin"), requestJson.getString("pbkdf2_salt"), requestJson.getString("aes_iv")); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("user_id", userId)); }); get("/folders/", (request, response) -> { ArrayList<JSONObject> folderObjects = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { List<DynaBean> folders = database.getFolders((int) Auth.getCurrentUser(request).get("id")); for (DynaBean folder : folders) { folderObjects.add(ResponseBuilder.objectOf("id", (int) folder.get("id"), "name", (String) folder.get("name"), "read", (boolean) folder.get("read"), "write", (boolean) folder.get("write"))); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("folders", ResponseBuilder.fromArrayList(folderObjects))); }); put("/folders/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "putFolder"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } Auth.enforceAdmin(request, response); int folderId = -1; try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.getFolder(requestJson.getString("name")); ResponseBuilder.errorHalt(response, 409, "A folder with that name already exists"); } catch (ObjectNotFoundException ex) { // We don't care if it doesn't exist, we actually want this exception to be thrown! } folderId = database.addFolder(requestJson.getString("name")); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("folder_id", folderId)); }); post("/folders/:folderId/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE); JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postFolders"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.updateFolder(folderId, requestJson.getString("name")); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); // TODO - Replace with generic update user method post("/users/self/update_password/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postUsersUpdatePassword"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.updateUserPassword(Auth.getCurrentUserId(request), requestJson.getString("encrypted_private_key"), requestJson.getString("aes_iv"), requestJson.getString("pbkdf2_salt"), BCrypt.hashpw(requestJson.getString("auth_key"), BCrypt.gensalt())); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "User not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); delete("/folders/:folderId/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.deleteFolder(folderId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/folders/:folderId/accounts/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_READ); ArrayList<JSONObject> accountObjects = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { List<DynaBean> accounts = new ArrayList<>(); accounts = database.getFolderAccounts(folderId, Auth.getCurrentUserId(request)); for (DynaBean account : accounts) { accountObjects.add(ResponseBuilder.objectOf("id", (int) account.get("account_id"), "account_metadata", (String) account.get("account_metadata"), "encrypted_aes_key", (String) account.get("encrypted_aes_key"))); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("accounts", ResponseBuilder.fromArrayList(accountObjects))); }); get("/folders/:folderId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); List<DynaBean> permissions = new ArrayList<>(); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { permissions = database.getFolderPermissions(Integer.parseInt(request.params(":folderId"))); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } } ArrayList<JSONObject> responseObjects = new ArrayList<>(); for (DynaBean permission : permissions) { responseObjects.add(ResponseBuilder.objectOf("user_id", (int) permission.get("user_id"), "read", (boolean) permission.get("read"), "write", (boolean) permission.get("write"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("permissions", ResponseBuilder.fromArrayList(responseObjects))); }); post("/folders/:folderId/permissions/", (request, response) -> { Auth.enforceAdmin(request, response); int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } JSONObject requestJson = RequestJson.getValidated(request, "postFoldersPermissions"); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.getFolder(folderId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found!"); } TransactionInterface transaction; try { transaction = new Transaction(database.getWrappedConnection()); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); } try { database.deleteFolderPermissions(folderId); JSONArray permissions = requestJson.getJSONArray("permissions"); for (int i = 0; i < permissions.length(); i++) { JSONObject permission = permissions.getJSONObject(i); int userId = permission.getInt("user_id"); boolean read = permission.getBoolean("read"); boolean write = permission.getBoolean("write"); try { DynaBean user = database.getUser(userId); if ((boolean) user.get("admin")) { transaction.rollback(); ResponseBuilder.errorHalt(response, 400, "Trying to set permissions " + "for an administrator, administrators already have full permission."); } } catch (ObjectNotFoundException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 404, "User not found!"); } if (write && !read) { transaction.rollback(); ResponseBuilder.errorHalt(response, 400, "Users must be able " + "to read a folder if they are to write to it"); } if (!(write || read)) { database.deleteAccountDataForFolder(folderId, userId); } else { database.addPermission(folderId, userId, read, write); } } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error updating permissions - " + ex); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); get("/folders/:folderId/public_keys/", (request, response) -> { int folderId = -1; try { folderId = Integer.parseInt(request.params(":folderId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Folder ID must be a number"); } Auth.enforceFolderPermission(request, response, folderId, Auth.PERMISSION_WRITE); List<DynaBean> users; try (Database database = new Database(ConnectionManager.getConnection(request))) { users = database.getFolderUsers(folderId); } ArrayList<JSONObject> publicKeyObjects = new ArrayList<>(); for (DynaBean user : users) { publicKeyObjects.add(ResponseBuilder.objectOf("user_id", (int) user.get("id"), "public_key", (String) user.get("public_key"))); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("public_keys", ResponseBuilder.fromArrayList(publicKeyObjects))); }); get("/accounts/:accountId/", (request, response) -> { int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_READ); DynaBean account = null; try (Database database = new Database(ConnectionManager.getConnection(request))) { try { account = database.getAccountData(accountId, Auth.getCurrentUserId(request)); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("account", ResponseBuilder.objectOf("account_metadata", (String) account.get("account_metadata"), "encrypted_aes_key", (String) account.get("encrypted_aes_key")))); }); delete("/accounts/:accountId/", (request, response) -> { int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.deleteAccount(accountId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/accounts/:accountId/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "postAccountsSingle"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, "JSON Validation Error - " + ex.getMessage()); } int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE); try (Database database = new Database(ConnectionManager.getConnection(request))) { try { database.getAccount(accountId); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } try { database.getFolder(requestJson.getInt("folder_id")); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } TransactionInterface transaction; try { transaction = new Transaction(database.getWrappedConnection()); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); } try { database.updateAccount(accountId, requestJson.getInt("folder_id")); JSONArray accountDataItems = requestJson.getJSONArray("encrypted_account_data"); for (int i = 0; i < accountDataItems.length(); i++) { JSONObject accountDataItem = accountDataItems.getJSONObject(i); int userId = accountDataItem.getInt("user_id"); database.deleteAccountData(accountId, userId); database.addAccountDataItem(accountId, userId, accountDataItem.getString("account_metadata"), accountDataItem.getString("password"), accountDataItem.getString("encrypted_aes_key")); } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error saving account - " + ex); } catch (ObjectNotFoundException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 404, "Error saving account - Object Not Found"); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/accounts/", (request, response) -> { JSONObject requestJson = RequestJson.getValidated(request, "postAccountsBatch"); JSONArray accounts = requestJson.getJSONArray("accounts"); try (Database database = new Database(ConnectionManager.getConnection(request))) { TransactionInterface transaction; try { transaction = new Transaction(database.getWrappedConnection()); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); } try { for (int i = 0; i < accounts.length(); i++) { JSONObject account = accounts.getJSONObject(i); int accountId = account.getInt("account_id"); try { if (!Auth.getAccountPermission(request, response, accountId, Auth.PERMISSION_WRITE)) { transaction.rollback(); ResponseBuilder.errorHalt(response, 403, "You do not have write permission for account " + accountId); } } catch (ObjectNotFoundException ex) { transaction.rollback(); ex.printStackTrace(); ResponseBuilder.errorHalt(response, 404, "Account not found"); } JSONArray accountDataItems = account.getJSONArray("encrypted_account_data"); for (int j = 0; j < accountDataItems.length(); j++) { JSONObject accountDataItem = accountDataItems.getJSONObject(j); int userId = accountDataItem.getInt("user_id"); database.deleteAccountData(accountId, userId); database.addAccountDataItem(accountId, userId, accountDataItem.getString("account_metadata"), accountDataItem.getString("password"), accountDataItem.getString("encrypted_aes_key")); } } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error saving accounts - " + ex); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); put("/accounts/", (request, response) -> { JSONObject requestJson = null; try { requestJson = RequestJson.getValidated(request, "putAccounts"); } catch (JSONValidationException ex) { // TODO: Friendly error messages for JSONValidationExceptions rather than raw output from validation library ResponseBuilder.errorHalt(response, 400, ex.getMessage()); } Auth.enforceFolderPermission(request, response, requestJson.getInt("folder_id"), Auth.PERMISSION_WRITE); int accountId = -1; WrappedConnection connection = ConnectionManager.getConnection(request); try (Database database = new Database(connection)) { try { database.getFolder(requestJson.getInt("folder_id")); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Folder not found"); } TransactionInterface transaction; try { transaction = new Transaction(connection); } catch (ExistingOpenTransactionException ex) { transaction = new NullTransaction(); Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } try { accountId = database.addAccount(requestJson.getInt("folder_id")); JSONArray accountDataItems = requestJson.getJSONArray("encrypted_account_data"); for (int i = 0; i < accountDataItems.length(); i++) { JSONObject accountDataItem = accountDataItems.getJSONObject(i); database.addAccountDataItem(accountId, accountDataItem.getInt("user_id"), accountDataItem.getString("account_metadata"), accountDataItem.getString("password"), accountDataItem.getString("encrypted_aes_key")); } } catch (SQLException ex) { transaction.rollback(); ResponseBuilder.errorHalt(response, 500, "Error adding account - " + ex); } transaction.commit(); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("account_id", accountId)); }); get("/accounts/:accountId/password/", (request, response) -> { int accountId = -1; try { accountId = Integer.parseInt(request.params(":accountId")); } catch (NumberFormatException ex) { ResponseBuilder.errorHalt(response, 400, "Account ID must be a number"); } Auth.enforceAccountPermission(request, response, accountId, Auth.PERMISSION_READ); DynaBean account = null; try (Database database = new Database(ConnectionManager.getConnection(request))) { try { account = database.getAccountData(accountId, Auth.getCurrentUserId(request)); } catch (ObjectNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Account not found"); } } return ResponseBuilder.build(response, ResponseBuilder.objectOf("password", ResponseBuilder.objectOf("encrypted_password", (String) account.get("password"), "encrypted_aes_key", (String) account.get("encrypted_aes_key")))); }); put("/transaction/", (request, response) -> { Transaction transaction = TransactionStore.getTransaction(); return ResponseBuilder.build(response, ResponseBuilder.objectOf("transaction_id", transaction.getId())); }); post("/transaction/:transactionId/commit/", (request, response) -> { String transactionId = request.params(":transactionId"); try { Transaction transaction = TransactionStore.getTransaction(transactionId); transaction.commit(); transaction.getWrappedConnection().getConnection().close(); TransactionStore.forgetTransaction(transactionId); } catch (TransactionNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Transaction not found!"); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); post("/transaction/:transactionId/rollback/", (request, response) -> { String transactionId = request.params(":transactionId"); try { Transaction transaction = TransactionStore.getTransaction(transactionId); transaction.rollback(); transaction.getWrappedConnection().getConnection().close(); TransactionStore.forgetTransaction(transactionId); } catch (TransactionNotFoundException ex) { ResponseBuilder.errorHalt(response, 404, "Transaction not found!"); } return ResponseBuilder.build(response, ResponseBuilder.objectOf("success", true)); }); exception(Exception.class, (e, request, response) -> { if (e.getClass().equals(TransactionNotFoundException.class)) { response.status(404); response.body(ResponseBuilder.objectOf("error", true, "message", "Transaction not found", "type", "transaction_not_found").toString()); } else { System.out.println("An unhandled exception occurred!"); System.out.println(e.toString()); e.printStackTrace(); response.status(500); response.type("application/json"); response.body(ResponseBuilder .objectOf("error", true, "message", "An unhandled server error occurred! - " + e.toString()) .toString()); } }); //TODO - Disable this in production! // spark.debug.DebugScreen.enableDebugScreen(); }
From source file:com.diversityarrays.dal.server.DalServer.java
public static void main(String[] args) { String host = null;/*from www.j a v a 2 s. c om*/ int port = DalServerUtil.DEFAULT_DAL_SERVER_PORT; int inactiveMins = DalServerUtil.DEFAULT_MAX_INACTIVE_MINUTES; File docRoot = null; String serviceName = null; for (int i = 0; i < args.length; ++i) { String argi = args[i]; if (argi.startsWith("-")) { if ("--".equals(argi)) { break; } if ("-version".equals(argi)) { System.out.println(DAL_SERVER_VERSION); System.exit(0); } if ("-help".equals(argi)) { giveHelpThenExit(0); } if ("-docroot".equals(argi)) { if (++i >= args.length || args[i].startsWith("-")) { fatal("missing value for " + argi); } docRoot = new File(args[i]); } else if ("-sqllog".equals(argi)) { SqlUtil.logger = Logger.getLogger(SqlUtil.class.getName()); } else if ("-expire".equals(argi)) { if (++i >= args.length || args[i].startsWith("-")) { fatal("missing value for " + argi); } try { inactiveMins = Integer.parseInt(args[i], 10); if (inactiveMins <= 0) { fatal("invalid minutes: " + args[i]); } } catch (NumberFormatException e) { fatal("invalid minutes: " + args[i]); } } else if ("-localhost".equals(argi)) { host = "localhost"; } else if ("-port".equals(argi)) { if (++i >= args.length || args[i].startsWith("-")) { fatal("missing value for " + argi); } try { port = Integer.parseInt(args[i], 10); if (port < 0 || port > 65535) { fatal("invalid port number: " + args[i]); } } catch (NumberFormatException e) { fatal("invalid port number: " + args[i]); } } else { fatal("invalid option: " + argi); } } else { if (serviceName != null) { fatal("multiple serviceNames not supported: " + argi); } serviceName = argi; } } final DalServerPreferences preferences = new DalServerPreferences( Preferences.userNodeForPackage(DalServer.class)); if (docRoot == null) { docRoot = preferences.getWebRoot(new File(System.getProperty("user.dir"), "www")); } DalServer server = null; if (serviceName != null && docRoot.isDirectory()) { try { DalDatabase db = createDalDatabase(serviceName, preferences); if (db.isInitialiseRequired()) { Closure<String> progress = new Closure<String>() { @Override public void execute(String msg) { System.out.println("Database Initialisation: " + msg); } }; db.initialise(progress); } server = create(preferences, host, port, docRoot, db); } catch (NoServiceException e) { throw new RuntimeException(e); } catch (DalDbException e) { throw new RuntimeException(e); } } Image serverIconImage = null; InputStream imageIs = DalServer.class.getResourceAsStream("dalserver-24.png"); if (imageIs != null) { try { serverIconImage = ImageIO.read(imageIs); if (Util.isMacOS()) { try { MacApplication macapp = new MacApplication(null); macapp.setDockIconImage(serverIconImage); } catch (MacApplicationException e) { System.err.println(e.getMessage()); } } } catch (IOException ignore) { } } if (server != null) { server.setMaxInactiveMinutes(inactiveMins); } else { AskServerParams asker = new AskServerParams(serverIconImage, null, "DAL Server Start", docRoot, preferences); GuiUtil.centreOnScreen(asker); asker.setVisible(true); if (asker.cancelled) { System.exit(0); } host = asker.dalServerHostName; port = asker.dalServerPort; inactiveMins = asker.maxInactiveMinutes; server = create(preferences, host, port, asker.wwwRoot, asker.dalDatabase); // server.setUseSimpleDatabase(asker.useSimpleDatabase); } final DalServer f_server = server; final File f_wwwRoot = docRoot; final Image f_serverIconImage = serverIconImage; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { DalServerFactory factory = new DalServerFactory() { @Override public DalServer create(String hostName, int port, File wwwRoot, DalDatabase dalDatabase) { return DalServer.create(preferences, hostName, port, wwwRoot, dalDatabase); } }; ServerGui gui = new ServerGui(f_serverIconImage, f_server, factory, f_wwwRoot, preferences); gui.setVisible(true); } }); }
From source file:Main.java
public static double getDoubleAttribute(Element node, String attr) { double retValue = 0; try {// ww w . ja v a 2s. co m String s = node.getAttribute(attr); s = s.replace(',', '.'); //retValue = Double.parseDouble( s ); retValue = Double.valueOf(s).doubleValue(); } catch (NumberFormatException ex) { System.err.println("Parse error:" + ex.getMessage() + " while reading attr: " + attr); lastState = ERROR; } return retValue; }
From source file:com.dattack.dbping.cli.PingAnalyzerCli.java
private static Long parseLong(final String txt) { try {//from w w w. j av a 2 s .com if (txt != null) { return Long.valueOf(txt); } } catch (final NumberFormatException e) { System.err.println(e.getMessage()); } return null; }