List of usage examples for java.io PrintStream print
public void print(Object obj)
From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java
public static void main(String[] args) throws Exception { if (args.length < 5 || !areNCFiles(Arrays.copyOfRange(args, 3, args.length))) { throw new RuntimeException("Needs: \n" + "(1) mass value, e.g., 132.0772 for debugging, \n" + "(2) how many timepoints to process (-1 for all), \n" + "(3) prefix for .data and rendered .pdf \n" + "(4,5..) 2 or more NetCDF .nc files"); }// w w w .j a v a 2s . c o m String fmt = "pdf"; Double mz = Double.parseDouble(args[0]); Integer numSpectraToProcess = Integer.parseInt(args[1]); String outPrefix = args[2]; String outImg = outPrefix.equals("-") ? null : outPrefix + "." + fmt; String outData = outPrefix.equals("-") ? null : outPrefix + ".data"; CompareTwoNetCDFAroundMass c = new CompareTwoNetCDFAroundMass(); String[] netCDF_fnames = Arrays.copyOfRange(args, 3, args.length); List<List<Pair<Double, Double>>> spectra = c.getSpectraForMass(mz, netCDF_fnames, numSpectraToProcess); // Write data output to outfile PrintStream out = outData == null ? System.out : new PrintStream(new FileOutputStream(outData)); // print out the spectra to outData for (List<Pair<Double, Double>> spectraInFile : spectra) { for (Pair<Double, Double> xy : spectraInFile) { out.format("%.4f\t%.4f\n", xy.getLeft(), xy.getRight()); out.flush(); } // delimit this dataset from the rest out.print("\n\n"); } // find the ymax across all spectra, so that we can have a uniform y scale Double yrange = 0.0; for (List<Pair<Double, Double>> spectraInFile : spectra) { Double ymax = 0.0; for (Pair<Double, Double> xy : spectraInFile) { Double intensity = xy.getRight(); if (ymax < intensity) ymax = intensity; } if (yrange < ymax) yrange = ymax; } if (outData != null) { // if outData is != null, then we have written to .data file // now render the .data to the corresponding .pdf file // first close the .data out.close(); // render outData to outFILE using gnuplo Gnuplotter plotter = new Gnuplotter(); plotter.plot2D(outData, outImg, netCDF_fnames, "time in seconds", yrange, "intensity", fmt); } }
From source file:ArrayDictionary.java
/** * A kludge for testing ArrayDictionary//from w w w .j a va 2 s.c o m */ public static void main(String[] args) { try { PrintStream out = System.out; DataInputStream in = new DataInputStream(System.in); String line = null; out.print("n ? "); out.flush(); line = in.readLine(); int n = Integer.parseInt(line); ArrayDictionary ad = new ArrayDictionary(n); String key = null, value = null; while (true) { out.print("action ? "); out.flush(); line = in.readLine(); switch (line.charAt(0)) { case 'p': case 'P': out.print("key ? "); out.flush(); key = in.readLine(); out.print("value ? "); out.flush(); value = in.readLine(); value = (String) ad.put(key, value); out.println("old: " + value); break; case 'r': case 'R': out.print("key ? "); out.flush(); key = in.readLine(); value = (String) ad.remove(key); out.println("old: " + value); break; case 'g': case 'G': out.print("key ? "); out.flush(); key = in.readLine(); value = (String) ad.get(key); out.println("value: " + value); break; case 'd': case 'D': out.println(ad.toString()); break; case 'q': case 'Q': return; } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.act.lcms.AnimateNetCDFAroundMass.java
public static void main(String[] args) throws Exception { if (args.length < 7 || !areNCFiles(Arrays.copyOfRange(args, 5, args.length))) { throw new RuntimeException( "Needs: \n" + "(1) mass value, e.g., 132.0772 \n" + "(2) time value, e.g., 39.2, (seconds), \n" + "(3) minimum Mz Precision, 0.04 \n" + "(4) max z axis, e.g., 20000 \n" + "(5) prefix for .data and rendered .pdf \n" + "(6..) 2 or more NetCDF .nc files"); }//from www . j av a2s .com Double mz = Double.parseDouble(args[0]); Double time = Double.parseDouble(args[1]); Double minMzPrecision = Double.parseDouble(args[2]); Double maxZAxis = Double.parseDouble(args[3]); String outPrefix = args[4]; // the mz values go from 50-950, we start with a big window and exponentially narrow down double mzWin = 100; // time values go from 0-450, we start with a big window and exponentially narrow down double timeWin = 50; // the factor by which to zoom in every step (has to be >1, a value of 2 is good) double factor = 1.2; // the animation frame count int frame = 1; AnimateNetCDFAroundMass c = new AnimateNetCDFAroundMass(); String[] netCDFFnames = Arrays.copyOfRange(args, 5, args.length); List<List<XYZ>> spectra = c.getSpectra(netCDFFnames, time, timeWin, mz, mzWin); for (List<XYZ> s : spectra) { System.out.format("%d xyz datapoints in (initial narrowed) spectra\n", s.size()); } String[] labels = new String[netCDFFnames.length]; for (int i = 0; i < labels.length; i++) labels[i] = "Dataset: " + i; // you could set labels to netCDFFnames to get precise labels on the graphs Gnuplotter plotter = new Gnuplotter(); String fmt = "png"; List<String> outImgFiles = new ArrayList<>(), outDataFiles = new ArrayList<>(); while (mzWin > minMzPrecision) { // exponentially narrow windows down mzWin /= factor; timeWin /= factor; List<List<XYZ>> windowedSpectra = c.getSpectraInWindowAll(spectra, time, timeWin, mz, mzWin); String frameid = String.format("%03d", frame); String outPDF = outPrefix + frameid + "." + fmt; String outDATA = outPrefix + frameid + ".data"; outImgFiles.add(outPDF); outDataFiles.add(outDATA); frame++; // Write data output to outfile PrintStream out = new PrintStream(new FileOutputStream(outDATA)); // print out the spectra to outDATA for (List<XYZ> windowOfSpectra : windowedSpectra) { for (XYZ xyz : windowOfSpectra) { out.format("%.4f\t%.4f\t%.4f\n", xyz.time, xyz.mz, xyz.intensity); out.flush(); } // delimit this dataset from the rest out.print("\n\n"); } // close the .data out.close(); // render outDATA to outPDF using gnuplot plotter.plotMulti3D(outDATA, outPDF, fmt, labels, maxZAxis); } String outImgs = outPrefix + "*." + fmt; plotter.makeAnimatedGIF(outImgs, outPrefix + ".gif"); // all the frames are now in the animated gif, remove the intermediate files for (String f : outDataFiles) new File(f).delete(); for (String f : outImgFiles) new File(f).delete(); }
From source file:com.zimbra.cs.imap.ImapMessage.java
public static void main(String[] args) { PrintStream ps = new PrintStream(System.out); ps.print(ImapHandler.LINE_SEPARATOR_BYTES); String[] samples = new String[] { null, "test", "\u0442", "ha\nnd", "\"dog\"", "ca\"t", "\0fr\0og\0" }; for (String s : samples) { nstring2047(ps, s);//from www . jav a2 s. c om ps.write(' '); nstring(ps, s); ps.write(' '); astring(ps, s); ps.write(' '); aSTRING(ps, s); ps.write('\n'); } }
From source file:Redirect.java
public static void main(String args[]) throws Exception { PrintStream origOut = System.out; PrintStream origErr = System.err; InputStream stdin = null;/* w w w .j a v a 2 s . c om*/ stdin = new FileInputStream("Redirect.in"); PrintStream stdout = null; stdout = new PrintStream(new FileOutputStream("Redirect.out")); PrintStream stderr = null; stderr = new PrintStream(new FileOutputStream("Redirect.err")); origOut.println("1"); System.out.println("2"); origOut.println("3"); System.err.println("4"); origErr.println("5"); System.setIn(stdin); System.setOut(stdout); System.setErr(stderr); origOut.println("\nR"); System.out.println("T"); origOut.println("Tq"); System.err.println("Tqw"); origErr.println("Test"); origOut.println("\nRedirect: Round #3"); int inChar = 0; while (-1 != inChar) { try { inChar = System.in.read(); } catch (Exception e) { // Clean up the output and bail. origOut.print("\n"); break; } origOut.write(inChar); } stdin.close(); stdout.close(); stderr.close(); System.exit(0); }
From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java
/** * @param args// w w w.ja v a2 s . c o m */ public static void main(String[] args) { // Setup parameters int verbosity = 1; String output_format = "xml", grammar_filename = null, filename_to_parse = null; // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("f")) { output_format = c_line.getOptionValue("f"); } // Get grammar file @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no grammar file specified"); System.exit(ERR_ARGUMENTS); } grammar_filename = remaining_args.get(0); // Get file to parse, if any if (remaining_args.size() >= 2) { filename_to_parse = remaining_args.get(1); } // Read grammar file BnfParser parser = null; try { parser = new BnfParser(new File(grammar_filename)); } catch (InvalidGrammarException e) { System.err.println("ERROR: invalid grammar"); System.exit(ERR_GRAMMAR); } catch (IOException e) { System.err.println("ERROR reading grammar " + grammar_filename); System.exit(ERR_IO); } assert parser != null; // Read input file BufferedReader bis = null; if (filename_to_parse == null) { // Read from stdin bis = new BufferedReader(new InputStreamReader(System.in)); } else { // Read from file try { bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse)))); } catch (FileNotFoundException e) { System.err.println("ERROR: file not found " + filename_to_parse); System.exit(ERR_IO); } } assert bis != null; String str; StringBuilder input_file = new StringBuilder(); try { while ((str = bis.readLine()) != null) { input_file.append(str).append("\n"); } } catch (IOException e) { System.err.println("ERROR reading input"); System.exit(ERR_IO); } String file_contents = input_file.toString(); // Parse contents of file ParseNode p_node = null; try { p_node = parser.parse(file_contents); } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) { System.err.println("ERROR parsing input\n"); e.printStackTrace(); System.exit(ERR_PARSE); } if (p_node == null) { System.err.println("ERROR parsing input\n"); System.exit(ERR_PARSE); } assert p_node != null; // Output parse node to desired format PrintStream output = System.out; OutputFormatVisitor out_vis = null; if (output_format.compareToIgnoreCase("xml") == 0) { // Output to XML out_vis = new XmlVisitor(); } else if (output_format.compareToIgnoreCase("dot") == 0) { // Output to DOT out_vis = new GraphvizVisitor(); } else if (output_format.compareToIgnoreCase("txt") == 0) { // Output to indented plain text out_vis = new IndentedTextVisitor(); } else if (output_format.compareToIgnoreCase("json") == 0) { // Output to JSON } if (out_vis == null) { System.err.println("ERROR: unknown output format " + output_format); System.exit(ERR_ARGUMENTS); } assert out_vis != null; p_node.prefixAccept(out_vis); output.print(out_vis.toOutputString()); // Terminate without error System.exit(ERR_OK); }
From source file:ca.ualberta.exemplar.core.Exemplar.java
public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException { CommandLineParser cli = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "shows this message"); options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)"); options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)"); CommandLine line = null;/*from w w w .ja v a 2 s . co m*/ try { line = cli.parse(options, rawArgs); } catch (ParseException exp) { System.err.println(exp.getMessage()); System.exit(1); } String[] args = line.getArgs(); String parserName = line.getOptionValue("parser", "malt"); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sh ./exemplar", options); System.exit(0); } if (args.length != 2) { System.out.println("error: exemplar requires an input file and output file."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sh ./exemplar <input> <output>", options); System.exit(0); } File input = new File(args[0]); File output = new File(args[1]); String benchmarkType = line.getOptionValue("benchmark", ""); if (!benchmarkType.isEmpty()) { if (benchmarkType.equals("binary")) { BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName); evaluation.runAndTime(); System.exit(0); } else { if (benchmarkType.equals("nary")) { BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName); evaluation.runAndTime(); System.exit(0); } else { System.out.println("error: benchmark option has to be either 'binary' or 'nary'."); System.exit(0); } } } Parser parser = null; if (parserName.equals("stanford")) { parser = new ParserStanford(); } else { if (parserName.equals("malt")) { parser = new ParserMalt(); } else { System.out.println(parserName + " is not a valid parser."); System.exit(0); } } System.out.println("Starting EXEMPLAR..."); RelationExtraction exemplar = null; try { exemplar = new RelationExtraction(parser); } catch (FileNotFoundException e) { e.printStackTrace(); } BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE); PlainTextReader reader = null; reader = new PlainTextReader(inputQueue, input); Thread readerThread = new Thread(reader); readerThread.start(); PrintStream statementsOut = null; try { statementsOut = new PrintStream(output, "UTF-8"); } catch (FileNotFoundException e1) { e1.printStackTrace(); System.exit(0); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); System.exit(0); } statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence"); while (true) { String doc = null; try { doc = inputQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } if (doc.isEmpty()) { break; } List<RelationInstance> instances = exemplar.extractRelations(doc); for (RelationInstance instance : instances) { // Output SUBJ arguments in a separate field, for clarity boolean first = true; for (Argument arg : instance.getArguments()) { if (arg.argumentType.equals("SUBJ")) { if (first) { first = false; } else { statementsOut.print(",,"); } statementsOut.print(arg.argumentType + ":" + arg.entityId); } } // Output the original relation statementsOut.print("\t" + instance.getOriginalRelation() + "\t"); // Output the DOBJ arguments, followed by POBJ first = true; for (Argument arg : instance.getArguments()) { if (arg.argumentType.equals("DOBJ")) { if (first) { first = false; } else { statementsOut.print(",,"); } statementsOut.print(arg.argumentType + ":" + arg.entityId); } } for (Argument arg : instance.getArguments()) { if (arg.argumentType.startsWith("POBJ")) { if (first) { first = false; } else { statementsOut.print(",,"); } statementsOut.print(arg.argumentType + ":" + arg.entityId); } } statementsOut.print("\t" + instance.getNormalizedRelation()); statementsOut.print("\t" + instance.getSentence()); statementsOut.println(); } } System.out.println("Done!"); statementsOut.close(); }
From source file:co.cask.cdap.cli.CLIMain.java
public static void main(String[] args) { final PrintStream output = System.out; Options options = getOptions();// w ww .j av a 2s . co m CLIMainArgs cliMainArgs = CLIMainArgs.parse(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine command = parser.parse(options, cliMainArgs.getOptionTokens()); if (command.hasOption(HELP_OPTION.getOpt())) { usage(); System.exit(0); } LaunchOptions launchOptions = LaunchOptions.builder() .setUri(command.getOptionValue(URI_OPTION.getOpt(), getDefaultURI().toString())) .setDebug(command.hasOption(DEBUG_OPTION.getOpt())) .setVerifySSL(parseBooleanOption(command, VERIFY_SSL_OPTION, DEFAULT_VERIFY_SSL)) .setAutoconnect(parseBooleanOption(command, AUTOCONNECT_OPTION, DEFAULT_AUTOCONNECT)).build(); String scriptFile = command.getOptionValue(SCRIPT_OPTION.getOpt(), ""); boolean hasScriptFile = command.hasOption(SCRIPT_OPTION.getOpt()); String[] commandArgs = cliMainArgs.getCommandTokens(); try { ClientConfig clientConfig = ClientConfig.builder().setConnectionConfig(null).build(); final CLIConfig cliConfig = new CLIConfig(clientConfig, output, new AltStyleTableRenderer()); CLIMain cliMain = new CLIMain(launchOptions, cliConfig); CLI cli = cliMain.getCLI(); cliMain.tryAutoconnect(); CLIConnectionConfig connectionConfig = new CLIConnectionConfig( cliConfig.getClientConfig().getConnectionConfig(), Id.Namespace.DEFAULT, null); cliMain.updateCLIPrompt(connectionConfig); if (hasScriptFile) { File script = cliMain.getFilePathResolver().resolvePathToFile(scriptFile); if (!script.exists()) { output.println("ERROR: Script file '" + script.getAbsolutePath() + "' does not exist"); System.exit(1); } List<String> scriptLines = Files.readLines(script, Charsets.UTF_8); for (String scriptLine : scriptLines) { output.print(cliMain.getPrompt(connectionConfig)); output.println(scriptLine); cli.execute(scriptLine, output); output.println(); } } else if (commandArgs.length == 0) { cli.startInteractiveMode(output); } else { cli.execute(Joiner.on(" ").join(commandArgs), output); } } catch (Exception e) { e.printStackTrace(output); } } catch (ParseException e) { output.println(e.getMessage()); usage(); } }
From source file:com.genentech.struchk.oeStruchk.OEStruchk.java
/** * Command line interface to {@link OEStruchk}. *///from ww w . ja va 2 s .c om public static void main(String[] args) throws ParseException, JDOMException, IOException { long start = System.currentTimeMillis(); int nMessages = 0; int nErrors = 0; int nStruct = 0; System.err.printf("OEChem Version: %s\n", oechem.OEChemGetVersion()); // create command line Options object Options options = new Options(); Option opt = new Option("f", true, "specify the configuration file name"); opt.setRequired(false); options.addOption(opt); opt = new Option("noMsg", false, "Do not add any additional sd-tags to the sdf file"); options.addOption(opt); opt = new Option("printRules", true, "Print HTML listing all the rules to filename."); options.addOption(opt); opt = new Option("errorsAsWarnings", false, "Treat errors as warnings."); options.addOption(opt); opt = new Option("stopForDebug", false, "Stop and read from stdin for user tu start debugger."); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); args = cmd.getArgs(); if (cmd.hasOption("stopForDebug")) { BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in)); System.err.print("Please press return:"); localRdr.readLine(); } URL confFile; if (cmd.hasOption("f")) { confFile = new File(cmd.getOptionValue("f")).toURI().toURL(); } else { confFile = getResourceURL(OEStruchk.class, "Struchk.xml"); } boolean errorsAsWarnings = cmd.hasOption("errorsAsWarnings"); if (cmd.hasOption("printRules")) { String fName = cmd.getOptionValue("printRules"); PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(fName))); OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings); structFlagAssigner.printRules(out); out.close(); return; } if (args.length < 1) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("oeStruck", options); throw new Error("missing input file\n"); } BufferedReader in = null; try { in = new BufferedReader(new FileReader(args[0])); StringBuilder mol = new StringBuilder(); StringBuilder data = new StringBuilder(); PrintStream out = System.out; if (args.length > 1) out = new PrintStream(args[1]); // create OEStruchk from config file OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings); OEStruchk structFlagChecker = new OEStruchk(confFile, CHECKConfig.CHECKStructFlag, errorsAsWarnings); Pattern sFlagPat = Pattern.compile("<StructFlag>\\s*([^\\n\\r]+)"); String line; boolean inMolFile = true; boolean atEnd = false; while (!atEnd) { if ((line = in.readLine()) == null) { if ("".equals(mol.toString().trim())) break; if (!inMolFile) throw new Error("Invalid end of sd file!"); line = "$$$$"; atEnd = true; } if (line.startsWith("$$$$")) { OEStruchk oeStruchk; StructureFlag sFlag = null; Matcher mat = sFlagPat.matcher(data); if (!mat.find()) { oeStruchk = structFlagAssigner; } else { oeStruchk = structFlagChecker; sFlag = StructureFlag.fromString(mat.group(1)); } if (!oeStruchk.applyRules(mol.toString(), null, sFlag)) nErrors++; out.print(oeStruchk.getTransformedMolfile(null)); out.print(data); if (!cmd.hasOption("noMsg")) { List<Message> msgs = oeStruchk.getStructureMessages(null); if (msgs.size() > 0) { nMessages += msgs.size(); out.println("> <errors_oe2>"); for (Message msg : msgs) out.printf("%s: %s\n", msg.getLevel(), msg.getText()); out.println(); } //System.err.println(oeStruchk.getTransformedMolfile("substance")); out.printf("> <outStereo>\n%s\n\n", oeStruchk.getStructureFlag().getName()); out.printf("> <TISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles(null)); out.printf("> <TSMI>\n%s\n\n", oeStruchk.getTransformedSmiles(null)); out.printf("> <pISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles("parent")); out.printf("> <salt>\n%s\n\n", oeStruchk.getSaltCode()); out.printf("> <stereoCounts>\n%s.%s\n\n", oeStruchk.countChiralCentersStr(), oeStruchk.countStereoDBondStr()); } out.println(line); nStruct++; mol.setLength(0); data.setLength(0); inMolFile = true; } else if (!inMolFile || line.startsWith(">")) { inMolFile = false; data.append(line).append("\n"); } else { mol.append(line).append("\n"); } } structFlagAssigner.delete(); structFlagChecker.delete(); } catch (Exception e) { throw new Error(e); } finally { System.err.printf("Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors, nMessages, (System.currentTimeMillis() - start) / 1000); if (in != null) in.close(); } if (cmd.hasOption("stopForDebug")) { BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in)); System.err.print("Please press return:"); localRdr.readLine(); } }
From source file:net.massbank.validator.RecordValidator.java
public static void main(String[] args) { RequestDummy request;// ww w . j a v a 2 s.com PrintStream out = System.out; Options lvOptions = new Options(); lvOptions.addOption("h", "help", false, "show this help."); lvOptions.addOption("r", "recdata", true, "points to the recdata directory containing massbank records. Reads all *.txt files in there."); CommandLineParser lvParser = new BasicParser(); CommandLine lvCmd = null; try { lvCmd = lvParser.parse(lvOptions, args); if (lvCmd.hasOption('h')) { printHelp(lvOptions); return; } } catch (org.apache.commons.cli.ParseException pvException) { System.out.println(pvException.getMessage()); } String recDataPath = lvCmd.getOptionValue("recdata"); // --------------------------------------------- // ???? // --------------------------------------------- final String baseUrl = MassBankEnv.get(MassBankEnv.KEY_BASE_URL); final String dbRootPath = "./"; final String dbHostName = MassBankEnv.get(MassBankEnv.KEY_DB_HOST_NAME); final String tomcatTmpPath = "."; final String tmpPath = (new File(tomcatTmpPath + sdf.format(new Date()))).getPath() + File.separator; GetConfig conf = new GetConfig(baseUrl); int recVersion = 2; String selDbName = ""; Object up = null; // Was: file Upload boolean isResult = true; String upFileName = ""; boolean upResult = false; DatabaseAccess db = null; try { // ---------------------------------------------------- // ??? // ---------------------------------------------------- // if (FileUpload.isMultipartContent(request)) { // (new File(tmpPath)).mkdir(); // String os = System.getProperty("os.name"); // if (os.indexOf("Windows") == -1) { // isResult = FileUtil.changeMode("777", tmpPath); // if (!isResult) { // out.println(msgErr("[" + tmpPath // + "] chmod failed.")); // return; // } // } // up = new FileUpload(request, tmpPath); // } // ---------------------------------------------------- // ?DB???? // ---------------------------------------------------- List<String> dbNameList = Arrays.asList(conf.getDbName()); ArrayList<String> dbNames = new ArrayList<String>(); dbNames.add(""); File[] dbDirs = (new File(dbRootPath)).listFiles(); if (dbDirs != null) { for (File dbDir : dbDirs) { if (dbDir.isDirectory()) { int pos = dbDir.getName().lastIndexOf("\\"); String dbDirName = dbDir.getName().substring(pos + 1); pos = dbDirName.lastIndexOf("/"); dbDirName = dbDirName.substring(pos + 1); if (dbNameList.contains(dbDirName)) { // DB???massbank.conf???DB???? dbNames.add(dbDirName); } } } } if (dbDirs == null || dbNames.size() == 0) { out.println(msgErr("[" + dbRootPath + "] directory not exist.")); return; } Collections.sort(dbNames); // ---------------------------------------------------- // ? // ---------------------------------------------------- // if (FileUpload.isMultipartContent(request)) { // HashMap<String, String[]> reqParamMap = new HashMap<String, // String[]>(); // reqParamMap = up.getRequestParam(); // if (reqParamMap != null) { // for (Map.Entry<String, String[]> req : reqParamMap // .entrySet()) { // if (req.getKey().equals("ver")) { // try { // recVersion = Integer // .parseInt(req.getValue()[0]); // } catch (NumberFormatException nfe) { // } // } else if (req.getKey().equals("db")) { // selDbName = req.getValue()[0]; // } // } // } // } else { // if (request.getParameter("ver") != null) { // try { // recVersion = Integer.parseInt(request // .getParameter("ver")); // } catch (NumberFormatException nfe) { // } // } // selDbName = request.getParameter("db"); // } // if (selDbName == null || selDbName.equals("") // || !dbNames.contains(selDbName)) { // selDbName = dbNames.get(0); // } // --------------------------------------------- // // --------------------------------------------- out.println("Database: "); for (int i = 0; i < dbNames.size(); i++) { String dbName = dbNames.get(i); out.print("dbName"); if (dbName.equals(selDbName)) { out.print(" selected"); } if (i == 0) { out.println("------------------"); } else { out.println(dbName); } } out.println("Record Version : "); out.println(recVersion); out.println("Record Archive :"); // --------------------------------------------- // // --------------------------------------------- // HashMap<String, Boolean> upFileMap = up.doUpload(); // if (upFileMap != null) { // for (Map.Entry<String, Boolean> e : upFileMap.entrySet()) { // upFileName = e.getKey(); // upResult = e.getValue(); // break; // } // if (upFileName.equals("")) { // out.println(msgErr("please select file.")); // isResult = false; // } else if (!upResult) { // out.println(msgErr("[" + upFileName // + "] upload failed.")); // isResult = false; // } else if (!upFileName.endsWith(ZIP_EXTENSION) // && !upFileName.endsWith(MSBK_EXTENSION)) { // out.println(msgErr("please select [" // + UPLOAD_RECDATA_ZIP // + "] or [" // + UPLOAD_RECDATA_MSBK + "].")); // up.deleteFile(upFileName); // isResult = false; // } // } else { // out.println(msgErr("server error.")); // isResult = false; // } // up.deleteFileItem(); // if (!isResult) { // return; // } // --------------------------------------------- // ??? // --------------------------------------------- // final String upFilePath = (new File(tmpPath + File.separator // + upFileName)).getPath(); // isResult = FileUtil.unZip(upFilePath, tmpPath); // if (!isResult) { // out.println(msgErr("[" // + upFileName // + "] extraction failed. possibility of time-out.")); // return; // } // --------------------------------------------- // ?? // --------------------------------------------- final String recPath = (new File(dbRootPath + File.separator + selDbName)).getPath(); File tmpRecDir = new File(recDataPath); if (!tmpRecDir.isDirectory()) { tmpRecDir.mkdirs(); } // --------------------------------------------- // ??? // --------------------------------------------- // data? // final String recDataPath = (new File(tmpPath + File.separator // + RECDATA_DIR_NAME)).getPath() // + File.separator; // // if (!(new File(recDataPath)).isDirectory()) { // if (upFileName.endsWith(ZIP_EXTENSION)) { // out.println(msgErr("[" // + RECDATA_DIR_NAME // + "] directory is not included in the up-loading file.")); // } else if (upFileName.endsWith(MSBK_EXTENSION)) { // out.println(msgErr("The uploaded file is not record data.")); // } // return; // } // --------------------------------------------- // DB // --------------------------------------------- // db = new DatabaseAccess(dbHostName, selDbName); // isResult = db.open(); // if (!isResult) { // db.close(); // out.println(msgErr("not connect to database.")); // return; // } // --------------------------------------------- // ?? // --------------------------------------------- TreeMap<String, String> resultMap = validationRecord(db, out, recDataPath, recPath, recVersion); if (resultMap.size() == 0) { return; } // --------------------------------------------- // ? // --------------------------------------------- isResult = dispResult(out, resultMap); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (db != null) { db.close(); } File tmpDir = new File(tmpPath); if (tmpDir.exists()) { FileUtil.removeDir(tmpDir.getPath()); } } }