List of usage examples for java.lang StringBuilder append
@Override public StringBuilder append(double d)
From source file:de.huxhorn.lilith.Lilith.java
public static void main(String[] args) { {//from w w w .ja v a 2 s .c o m // initialize java.util.logging to use slf4j... Handler handler = new Slf4JHandler(); java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger(""); rootLogger.addHandler(handler); rootLogger.setLevel(java.util.logging.Level.WARNING); } StringBuilder appTitle = new StringBuilder(); appTitle.append(APP_NAME).append(" V").append(APP_VERSION); if (APP_SNAPSHOT) { // always append timestamp for SNAPSHOT appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")"); } CommandLineArgs cl = new CommandLineArgs(); JCommander commander = new JCommander(cl); Cat cat = new Cat(); commander.addCommand(Cat.NAME, cat); Tail tail = new Tail(); commander.addCommand(Tail.NAME, tail); Filter filter = new Filter(); commander.addCommand(Filter.NAME, filter); Index index = new Index(); commander.addCommand(Index.NAME, index); Md5 md5 = new Md5(); commander.addCommand(Md5.NAME, md5); Help help = new Help(); commander.addCommand(Help.NAME, help); try { commander.parse(args); } catch (ParameterException ex) { printAppInfo(appTitle.toString(), false); System.out.println(ex.getMessage() + "\n"); printHelp(commander); System.exit(-1); } if (cl.verbose) { if (!APP_SNAPSHOT) { // timestamp is always appended for SNAPSHOT // don't append it twice appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")"); } appTitle.append(" - ").append(APP_REVISION); } String appTitleString = appTitle.toString(); if (cl.showHelp) { printAppInfo(appTitleString, false); printHelp(commander); System.exit(0); } String command = commander.getParsedCommand(); if (!Tail.NAME.equals(command) && !Cat.NAME.equals(command) && !Filter.NAME.equals(command)) // don't print info in case of cat, tail or filter { printAppInfo(appTitleString, true); } if (cl.logbackConfig != null) { File logbackFile = new File(cl.logbackConfig); if (!logbackFile.isFile()) { System.out.println(logbackFile.getAbsolutePath() + " is not a valid file."); System.exit(-1); } try { initLogbackConfig(logbackFile.toURI().toURL()); } catch (MalformedURLException e) { System.out.println("Failed to convert " + logbackFile.getAbsolutePath() + " to URL. " + e); System.exit(-1); } } else if (cl.verbose) { initVerboseLogging(); } if (cl.printBuildTimestamp) { System.out.println("Build-Date : " + APP_TIMESTAMP_DATE); System.out.println("Build-Revision : " + APP_REVISION); System.out.println("Build-Timestamp: " + APP_TIMESTAMP); System.exit(0); } if (Help.NAME.equals(command)) { commander.usage(); if (help.commands == null || help.commands.size() == 0) { commander.usage(Help.NAME); } else { Map<String, JCommander> commands = commander.getCommands(); for (String current : help.commands) { if (commands.containsKey(current)) { commander.usage(current); } else { System.out.println("Unknown command '" + current + "'!"); } } } System.exit(0); } if (Md5.NAME.equals(command)) { List<String> files = md5.files; if (files == null || files.isEmpty()) { printHelp(commander); System.out.println("Missing files!"); System.exit(-1); } boolean error = false; for (String current : files) { if (!CreateMd5Command.createMd5(new File(current))) { error = true; } } if (error) { System.exit(-1); } System.exit(0); } if (Index.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = index.files; if (files == null || files.size() == 0) { printHelp(commander); System.exit(-1); } boolean error = false; for (String current : files) { if (!IndexCommand.indexLogFile(new File(current))) { error = true; } } if (error) { System.exit(-1); } System.exit(0); } if (Cat.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = cat.files; if (files == null || files.size() != 1) { printHelp(commander); System.exit(-1); } if (CatCommand.catFile(new File(files.get(0)), cat.pattern, cat.numberOfLines)) { System.exit(0); } System.exit(-1); } if (Tail.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = tail.files; if (files == null || files.size() != 1) { printHelp(commander); System.exit(-1); } if (TailCommand.tailFile(new File(files.get(0)), tail.pattern, tail.numberOfLines, tail.keepRunning)) { System.exit(0); } System.exit(-1); } if (Filter.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } if (FilterCommand.filterFile(new File(filter.input), new File(filter.output), new File(filter.condition), filter.searchString, filter.pattern, filter.overwrite, filter.keepRunning, filter.exclusive)) { System.exit(0); } System.exit(-1); } if (cl.flushPreferences) { flushPreferences(); } if (cl.exportPreferencesFile != null) { exportPreferences(cl.exportPreferencesFile); } if (cl.importPreferencesFile != null) { importPreferences(cl.importPreferencesFile); } if (cl.exportPreferencesFile != null || cl.importPreferencesFile != null) { System.exit(0); } if (cl.flushLicensed) { flushLicensed(); } startLilith(appTitleString); }
From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java
public static void main(String[] args) { String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a"; //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603"; //test();/*from w ww.j av a2 s. c o m*/ //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf"); // File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf"); File file = new File( "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf"); MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file); try { mbf.readFile(); } catch (IOException e) { //System.out.println(e.getMessage()); System.err.println( "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!"); System.exit(-1); } MetFusionBatchSettings settings = mbf.getBatchSettings(); List<String> absent = settings.getSubstrucAbsent(); List<String> present = settings.getSubstrucPresent(); for (String s : present) { System.out.println("present -> " + s); } for (String s : absent) { System.out.println("absent -> " + s); } String formula = settings.getMfFormula(); System.out.println("formula -> " + formula); boolean useFormulaAsQuery = true; boolean useSDF = false; String sdfFile = ""; if (useSDF) { sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf"; if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file? System.err.println("SDF file needs to be specified! Exiting."); System.exit(-1); } } SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery, useSDF, sdfFile); ss.run(); List<ResultSubstructure> remaining = ss.getResultsRemaining(); List<Result> resultsForSDF = new ArrayList<Result>(); StringBuilder sb = new StringBuilder(); String sep = ","; for (ResultSubstructure rs : remaining) { sb.append(rs.getId()).append(sep); Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore()); r.setMol(rs.getMol()); r.setSmiles(rs.getSmiles()); r.setInchi(rs.getInchi()); r.setInchikey(rs.getInchikey()); resultsForSDF.add(r); } String ids = sb.toString(); String fileSep = System.getProperty("file.separator"); if (!ids.isEmpty()) { ids = ids.substring(0, ids.length() - 1); System.out.println("ids -> " + ids); settings.setMfDatabaseIDs(ids); String filename = file.getName(); String prefix = filename.substring(0, filename.lastIndexOf(".")); filename = filename.replace(prefix, prefix + "_ids"); String dir = file.getParent(); System.out.println("dir -> " + dir); if (!dir.endsWith(fileSep)) dir += fileSep; File output = new File(file.getParent(), filename); mbf.writeFile(output, settings); SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf"); boolean writeOK = so.writeOriginalResults(resultsForSDF, false); if (!writeOK) System.err.println("Error writing SDF [" + so.getFilename()); } }
From source file:com.kactech.otj.examples.App_otj.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String command = null;//from www . j a v a2 s . co m String hisacct = null; String hisacctName = null; String hisacctAsset = null; String asset = null; String assetName = null; List<String> argList = null; boolean newAccount = false; File dir = null; ConnectionInfo connection = null; List<ScriptFilter> filters = null; CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println("Command-line parsing error: " + e.getMessage()); help(); System.exit(-1); } if (cmd.hasOption('h')) { help(); System.exit(0); } @SuppressWarnings("unchecked") List<String> list = cmd.getArgList(); if (list.size() > 1) { System.err.println("only one command is supported, you've typed " + list); help(); System.exit(-1); } if (list.size() > 0) command = list.get(0).trim(); List<SampleAccount> accounts = ExamplesUtils.getSampleAccounts(); if (cmd.hasOption('s')) { String v = cmd.getOptionValue('s').trim(); connection = ExamplesUtils.findServer(v); if (connection == null) { System.err.println("unknown server: " + v); System.exit(-1); } } else { connection = ExamplesUtils.findServer(DEF_SERVER_NAME); if (connection == null) { System.err.println("default server not found server: " + DEF_SERVER_NAME); System.exit(-1); } } if (cmd.hasOption('t')) { String v = cmd.getOptionValue('t'); for (SampleAccount ac : accounts) if (ac.accountName.startsWith(v)) { hisacct = ac.accountID; hisacctName = ac.accountName; hisacctAsset = ac.assetID; break; } if (hisacct == null) if (mayBeValid(v)) hisacct = v; else { System.err.println("invalid hisacct: " + v); System.exit(-1); } } if (cmd.hasOption('p')) { String v = cmd.getOptionValue('p'); for (SampleAccount ac : accounts) if (ac.assetName.startsWith(v)) { asset = ac.assetID; assetName = ac.assetName; break; } if (asset == null) if (mayBeValid(v)) asset = v; else { System.err.println("invalid asset: " + v); System.exit(-1); } } if (cmd.hasOption('a')) { String v = cmd.getOptionValue('a'); argList = new ArrayList<String>(); boolean q = false; StringBuilder b = new StringBuilder(); for (int i = 0; i < v.length(); i++) { char c = v.charAt(i); if (c == '"') { if (q) { argList.add(b.toString()); b = null; q = false; continue; } if (b != null) argList.add(b.toString()); b = new StringBuilder(); q = true; continue; } if (c == ' ' || c == '\t') { if (q) { b.append(c); continue; } if (b != null) argList.add(b.toString()); b = null; continue; } if (b == null) b = new StringBuilder(); b.append(c); } if (b != null) argList.add(b.toString()); if (q) { System.err.println("unclosed quote in args: " + v); System.exit(-1); } } dir = new File(cmd.hasOption('d') ? cmd.getOptionValue('d') : DEF_CLIENT_DIR); if (cmd.hasOption('x')) del(dir); newAccount = cmd.hasOption('n'); if (cmd.hasOption('f')) { filters = new ArrayList<ScriptFilter>(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Compilable compilingEngine = (Compilable) engine; for (String fn : cmd.getOptionValue('f').split(",")) { fn = fn.trim(); if (fn.isEmpty()) continue; fn += ".js"; Reader r = null; try { r = new InputStreamReader(new FileInputStream(new File("filters", fn)), Utils.UTF8); } catch (Exception e) { try { r = new InputStreamReader( App_otj.class.getResourceAsStream("/com/kactech/otj/examples/filters/" + fn)); } catch (Exception e2) { } } if (r == null) { System.err.println("filter not found: " + fn); System.exit(-1); } else try { CompiledScript compiled = compilingEngine.compile(r); ScriptFilter sf = new ScriptFilter(compiled); filters.add(sf); } catch (Exception ex) { System.err.println("error while loading " + fn + ": " + ex); System.exit(-1); } } } System.out.println("server: " + connection.getEndpoint() + " " + connection.getID()); System.out.println("command: '" + command + "'"); System.out.println("args: " + argList); System.out.println("hisacct: " + hisacct); System.out.println("hisacctName: " + hisacctName); System.out.println("hisacctAsset: " + hisacctAsset); System.out.println("asset: " + asset); System.out.println("assetName: " + assetName); if (asset != null && hisacctAsset != null && !asset.equals(hisacctAsset)) { System.err.println("asset differs from hisacctAsset"); System.exit(-1); } EClient client = new EClient(dir, connection); client.setAssetType(asset != null ? asset : hisacctAsset); client.setCreateNewAccount(newAccount); if (filters != null) client.setFilters(filters); try { Utils.init(); Client.DEBUG_JSON = true; client.init(); if ("balance".equals(command)) System.out.println("Balance: " + client.getAccount().getBalance().getAmount()); else if ("acceptall".equals(command)) client.processInbox(); else if ("transfer".equals(command)) { if (hisacct == null) System.err.println("please specify --hisacct"); else { int idx = argList != null ? argList.indexOf("amount") : -1; if (idx < 0) System.err.println("please specify amount"); else if (idx == argList.size()) System.err.println("amount argument needs value"); else { Long amount = -1l; try { amount = new Long(argList.get(idx + 1)); } catch (Exception e) { } if (amount <= 0) System.err.println("invalid amount"); else { client.notarizeTransaction(hisacct, amount); } } } } else if ("reload".equals(command)) client.reloadState(); else if ("procnym".equals(command)) client.processNymbox(); } finally { client.saveState(); client.close(); } }
From source file:an.dpr.cyclingresultsapi.ClientExecuteProxy.java
public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); StringBuilder ret = new StringBuilder(); try {/*from w w w . j ava 2 s . c o m*/ //http://cyclingresults-dprsoft.rhcloud.com/rest/competitions/query/20140101,20140601,1,1,UWT // HttpHost target = new HttpHost("cyclingresults-dprsoft.rhcloud.com", 80, "http"); HttpHost proxy = null;// = new HttpHost("proxy.sdc.hp.com", 8080, "http"); HttpHost target = new HttpHost("localhost", 8282, "http"); RequestConfig config = RequestConfig.custom() // .setProxy(proxy) .build(); HttpGet request = new HttpGet("/rest/competitions/query/20130801,20130901,1,1,UWT"); request.setConfig(config); System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy); CloseableHttpResponse response = httpclient.execute(target, request); InputStreamReader isr = new InputStreamReader(response.getEntity().getContent(), "cp1252"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { ret.append(line); } try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } finally { httpclient.close(); } System.out.println(ret.toString()); }
From source file:com.zimbra.common.calendar.ZoneInfo2iCalendar.java
public static void main(String[] args) throws Exception { // command line handling CommandLine cl = null;/*from ww w . j ava 2s .c o m*/ Params params = null; try { cl = parseArgs(args); if (cl.hasOption(OPT_HELP)) { usage(null); System.exit(0); } params = initParams(cl); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); System.exit(1); } // parse tzdata source ZoneInfoParser parser = new ZoneInfoParser(); for (File tzdataFile : params.tzdataFiles) { Reader r = null; try { r = new InputStreamReader(new FileInputStream(tzdataFile), "UTF-8"); parser.readTzdata(r); } catch (ParseException e) { System.err.println(e.getMessage()); System.err.println("Line: " + e.getErrorOffset()); System.err.println("File: " + tzdataFile.getAbsolutePath()); e.printStackTrace(); System.exit(1); } finally { if (r != null) r.close(); } } parser.analyze(); // read extra data file containing primary TZ list and zone match scores if (params.extraDataFile != null) { Reader r = null; try { r = new InputStreamReader(new FileInputStream(params.extraDataFile), "UTF-8"); readExtraData(r); } catch (ParseException e) { System.err.println(e.getMessage()); System.err.println("Line: " + e.getErrorOffset()); System.err.println("File: " + params.extraDataFile.getAbsolutePath()); e.printStackTrace(); System.exit(1); } finally { if (r != null) r.close(); } } Writer out; if (params.outputFile != null) { out = new PrintWriter(params.outputFile, "UTF-8"); } else { out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")); } try { StringBuilder hdr = new StringBuilder("BEGIN:VCALENDAR"); hdr.append(CRLF); hdr.append("PRODID:Zimbra-Calendar-Provider").append(CRLF); hdr.append("VERSION:2.0").append(CRLF); hdr.append("METHOD:PUBLISH").append(CRLF); out.write(hdr.toString()); Map<String, VTimeZone> oldTimeZones = makeOldTimeZonesMap(params); Set<Zone> zones = new TreeSet<Zone>(new ZoneComparatorByGmtOffset()); zones.addAll(parser.getZones()); Set<String> zoneIDs = new TreeSet<String>(); for (Zone zone : zones) { zoneIDs.add(zone.getName()); } for (Zone zone : zones) { out.write(getTimeZoneForZone(zone, params, zoneIDs, oldTimeZones)); } StringBuilder footer = new StringBuilder("END:VCALENDAR"); footer.append(CRLF); out.write(footer.toString()); } finally { out.close(); } }
From source file:com.genentech.struchk.sdfNormalizer.java
public static void main(String[] args) { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; // create command line Options object Options options = new Options(); Option opt = new Option("in", true, "input file [.ism,.sdf,...]"); opt.setRequired(true);//from w w w.ja v a 2 s . co m options.addOption(opt); opt = new Option("out", true, "output file"); opt.setRequired(true); options.addOption(opt); opt = new Option("mol", true, "molFile used for output: ORIGINAL(def)|NORMALIZED|TAUTOMERIC"); opt.setRequired(false); options.addOption(opt); opt = new Option("shortMessage", false, "Limit message to first 80 characters to conform with sdf file specs."); opt.setRequired(false); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { exitWithHelp(options, e.getMessage()); throw new Error(e); // avoid compiler errors } args = cmd.getArgs(); if (args.length != 0) { System.err.print("Unknown options: " + args + "\n\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sdfNormalizer", options); System.exit(1); } String molOpt = cmd.getOptionValue("mol"); OUTMolFormat outMol = OUTMolFormat.ORIGINAL; if (molOpt == null || "original".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.ORIGINAL; else if ("NORMALIZED".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.NORMALIZED; else if ("TAUTOMERIC".equalsIgnoreCase(molOpt)) outMol = OUTMolFormat.TAUTOMERIC; else { System.err.printf("Unkown option for -mol: %s\n", molOpt); System.exit(1); } String inFile = cmd.getOptionValue("in"); String outFile = cmd.getOptionValue("out"); boolean limitMessage = cmd.hasOption("shortMessage"); try { oemolistream ifs = new oemolistream(inFile); oemolostream ofs = new oemolostream(outFile); URL cFile = OEStruchk.getResourceURL(OEStruchk.class, "Struchk.xml"); // create OEStruchk from config file OEStruchk strchk = new OEStruchk(cFile, CHECKConfig.ASSIGNStructFlag, false); OEGraphMol mol = new OEGraphMol(); StringBuilder sb = new StringBuilder(2000); while (oechem.OEReadMolecule(ifs, mol)) { if (!strchk.applyRules(mol, null)) nErrors++; switch (outMol) { case NORMALIZED: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol("parent")); break; case TAUTOMERIC: mol.Clear(); oechem.OEAddMols(mol, strchk.getTransformedMol(null)); break; case ORIGINAL: break; } oechem.OESetSDData(mol, "CTISMILES", strchk.getTransformedIsoSmiles(null)); oechem.OESetSDData(mol, "CTSMILES", strchk.getTransformedSmiles(null)); oechem.OESetSDData(mol, "CISMILES", strchk.getTransformedIsoSmiles("parent")); oechem.OESetSDData(mol, "Strutct_Flag", strchk.getStructureFlag().getName()); List<Message> msgs = strchk.getStructureMessages(null); nMessages += msgs.size(); for (Message msg : msgs) sb.append(String.format("\t%s:%s", msg.getLevel(), msg.getText())); if (limitMessage) sb.setLength(Math.min(sb.length(), 80)); oechem.OESetSDData(mol, "NORM_MESSAGE", sb.toString()); oechem.OEWriteMolecule(ofs, mol); sb.setLength(0); nStruct++; } strchk.delete(); mol.delete(); ifs.close(); ifs.delete(); ofs.close(); ofs.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("sdfNormalizer: Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); } }
From source file:com.github.codingtogenomic.CodingToGenomic.java
public static void main(String[] args) throws Exception { //parse commandline Options options = new Options(); CommandLineParser parser = new PosixParser(); String gene = new String(); String transcript = new String(); String species = "human"; boolean mapCdna = false; String coordinate = new String(); StringBuilder errorMsg = new StringBuilder(); try {/*from ww w.ja v a2 s. c om*/ options = getOptions(args); } catch (org.apache.commons.cli.ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); System.exit(1); } CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { showHelp(options); } if (line.hasOption("gene")) { gene = line.getOptionValue("gene"); } else { if (!line.hasOption("transcript")) { errorMsg.append("Either --gene or --transcript argument is required\n"); } } if (line.hasOption("transcript")) { if (line.hasOption("gene")) { errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n"); } else { transcript = line.getOptionValue("transcript"); if (line.hasOption("species")) { System.out.println("Ignoring --species option when using --transcript argument"); } } } if (line.hasOption("coordinate")) { coordinate = line.getOptionValue("coordinate"); } else { errorMsg.append("--coordinate argument is required\n"); } if (line.hasOption("species")) { species = line.getOptionValue("species").replaceAll("\\s+", "_"); } if (line.hasOption("b37")) { if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) { SERVER = GRCh37Server; } else { System.out.println("--b37 argument will be ignored - it can only be " + "used when human is the species of interest. Current species" + " is " + species + ".\n"); } } if (line.hasOption("noncoding")) { mapCdna = true; } if (errorMsg.length() > 0) { showHelp(options, errorMsg.toString(), 2); } int c = 0; boolean threePrimeUtr = false; String prefix = "c."; if (mapCdna) { prefix = "n."; try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } else if (coordinate.startsWith("*")) { threePrimeUtr = true; prefix = "c.*"; String coord = coordinate.replaceFirst("\\*", ""); try { c = Integer.parseInt(coord); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer or UTR coordinate", 2); } } else { try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } //got arguments String result; String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate"; if (!gene.isEmpty()) { IdParser idParser = new IdParser(gene); System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType()); if (idParser.isEnsemblId()) { if (line.hasOption("species")) { System.out.println("Ignoring --species option when searching Ensembl ID."); } if (idParser.isTranscript()) { result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna); } else if (idParser.isEnsp()) { result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna); } } else { if (idParser.isTranscript()) { //append user input to beginning result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna); } } if (idParser.isTranscript() || idParser.isEnsp()) { result = gene + ":" + prefix + c + "\t" + result; } else { result = convertGeneResult(result, gene, c, prefix); } } else { System.out.println("Searching for " + transcript + " as Ensembl transcript ID"); result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna); //append user input to beginning result = transcript + ":" + prefix + c + "\t" + result; } System.out.println(header); System.out.println(result); }
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) -> {// w w w .j a v a 2s . c om // 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:HelloSmartsheet.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try {//from www .j av a 2 s. c om System.out.println("STARTING HelloSmartsheet..."); //Create a BufferedReader to read user input. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Smartsheet API access token:"); String accessToken = in.readLine(); System.out.println("Fetching list of your sheets..."); //Create a connection and fetch the list of sheets connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; //Read the response line by line. while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); //Use Jackson to conver the JSON string to a List of Sheets List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() { }); if (sheets.size() == 0) { System.out.println("You don't have any sheets. Goodbye!"); return; } System.out.println("Total sheets: " + sheets.size()); int i = 1; for (Sheet sheet : sheets) { System.out.println(i++ + ": " + sheet.name); } System.out.print("Enter the number of the sheet you want to share: "); //Prompt the user to provide the sheet number, the email address, and the access level Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected. Sheet chosenSheet = sheets.get(sheetNumber - 1); System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: "); String email = in.readLine(); System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": "); String accessLevel = in.readLine(); //Create a share object Share share = new Share(); share.setEmail(email); share.setAccessLevel(accessLevel); System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + "."); //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's') connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId())) .openConnection(); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); //Serialize the Share object writer.write(mapper.writeValueAsString(share)); writer.close(); //Read the response and parse the JSON reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } Result result = mapper.readValue(response.toString(), Result.class); System.out.println("Sheet shared successfully, share ID " + result.result.id); System.out.println("Press any key to quit."); in.read(); } catch (IOException e) { BufferedReader reader = new BufferedReader( new InputStreamReader(((HttpURLConnection) connection).getErrorStream())); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result result = mapper.readValue(response.toString(), Result.class); System.out.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:edu.cuhk.hccl.TripRealRatingsApp.java
public static void main(String[] args) throws IOException { File dir = new File(args[0]); File outFile = new File(args[1]); outFile.delete();/*from w w w. jav a 2s . c o m*/ StringBuilder buffer = new StringBuilder(); for (File file : dir.listFiles()) { List<String> lines = FileUtils.readLines(file, "UTF-8"); String hotelID = file.getName().split("_")[1]; String author = null; boolean noContent = false; for (String line : lines) { if (line.startsWith("<Author>")) { try { author = line.split(">")[1].trim(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("[ERROR] An error occured on this line:"); System.out.println(line); continue; } } else if (line.startsWith("<Content>")) { // ignore records if they have no content String content = line.split(">")[1].trim(); if (content == null || content.equals("")) noContent = true; } else if (line.startsWith("<Rating>")) { String[] rates = line.split(">")[1].trim().split("\t"); if (noContent || rates.length != 8) continue; // Change missing rating from -1 to 0 for (int i = 0; i < rates.length; i++) { if (rates[i].equals("-1")) rates[i] = "0"; } buffer.append(author + "\t"); buffer.append(hotelID + "\t"); // overall buffer.append(rates[0] + "\t"); // location buffer.append(rates[3] + "\t"); // room buffer.append(rates[2] + "\t"); // service buffer.append(rates[6] + "\t"); // value buffer.append(rates[1] + "\t"); // cleanliness buffer.append(rates[4] + "\t"); buffer.append("\n"); } } // Write once for each file FileUtils.writeStringToFile(outFile, buffer.toString(), true); // Clear buffer buffer.setLength(0); System.out.printf("[INFO] Finished processing %s\n", file.getName()); } System.out.println("[INFO] All processinig are finished!"); }