List of usage examples for java.lang StringBuffer toString
@Override @HotSpotIntrinsicCandidate public synchronized String toString()
From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulator.java
public static void main(String[] args) { boolean isTTY = (System.console() != null); long startTime = System.currentTimeMillis(); try {//from ww w . j a v a 2s . co m SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser theParser = parserFactory.newSAXParser(); TNT4JSimulatorParserHandler xmlHandler = new TNT4JSimulatorParserHandler(); processArgs(xmlHandler, args); TrackerConfig simConfig = DefaultConfigFactory.getInstance().getConfig(TNT4JSimulator.class.getName()); logger = TrackingLogger.getInstance(simConfig.build()); if (logger.isSet(OpLevel.TRACE)) traceLevel = OpLevel.TRACE; else if (logger.isSet(OpLevel.DEBUG)) traceLevel = OpLevel.DEBUG; if (runType == SimulatorRunType.RUN_SIM) { if (StringUtils.isEmpty(simFileName)) { simFileName = "tnt4j-sim.xml"; String fileName = readFromConsole("Simulation file [" + simFileName + "]: "); if (!StringUtils.isEmpty(fileName)) simFileName = fileName; } StringBuffer simDef = new StringBuffer(); BufferedReader simLoader = new BufferedReader(new FileReader(simFileName)); String line; while ((line = simLoader.readLine()) != null) simDef.append(line).append("\n"); simLoader.close(); info("jKool Activity Simulator Run starting: file=" + simFileName + ", iterations=" + numIterations + ", ttl.sec=" + ttl); startTime = System.currentTimeMillis(); if (isTTY && numIterations > 1) System.out.print("Iteration: "); int itTrcWidth = 0; for (iteration = 1; iteration <= numIterations; iteration++) { itTrcWidth = printProgress("Executing Iteration", iteration, itTrcWidth); theParser.parse(new InputSource(new StringReader(simDef.toString())), xmlHandler); if (!Utils.isEmpty(jkFileName)) { PrintWriter gwFile = new PrintWriter(new FileOutputStream(jkFileName, true)); gwFile.println(""); gwFile.close(); } } if (numIterations > 1) System.out.println(""); info("jKool Activity Simulator Run finished, elapsed time = " + DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - startTime)); printMetrics(xmlHandler.getSinkStats(), "Total Sink Statistics"); } else if (runType == SimulatorRunType.REPLAY_SIM) { info("jKool Activity Simulator Replay starting: file=" + jkFileName + ", iterations=" + numIterations); connect(); startTime = System.currentTimeMillis(); // Determine number of lines in file BufferedReader gwFile = new BufferedReader(new java.io.FileReader(jkFileName)); for (numIterations = 0; gwFile.readLine() != null; numIterations++) ; gwFile.close(); // Reopen the file and gwFile = new BufferedReader(new java.io.FileReader(jkFileName)); if (isTTY && numIterations > 1) System.out.print("Processing Line: "); int itTrcWidth = 0; String gwMsg; iteration = 0; while ((gwMsg = gwFile.readLine()) != null) { iteration++; if (isTTY) itTrcWidth = printProgress("Processing Line", iteration, itTrcWidth); gwConn.write(gwMsg); } if (isTTY && numIterations > 1) System.out.println(""); long endTime = System.currentTimeMillis(); info("jKool Activity Simulator Replay finished, elasped.time = " + DurationFormatUtils.formatDurationHMS(endTime - startTime)); } } catch (Exception e) { if (e instanceof SAXParseException) { SAXParseException spe = (SAXParseException) e; error("Error at line: " + spe.getLineNumber() + ", column: " + spe.getColumnNumber(), e); } else { error("Error running simulator", e); } } finally { try { Thread.sleep(1000L); } catch (Exception e) { } TNT4JSimulator.disconnect(); } System.exit(0); }
From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java
/** Starts a StrategyPlotter. * @param parameters//from ww w. java 2 s . c om * <pre> * Optional Parameters and default values: * -initialCash $10,000.00 * -perTradeFee $1.00 * -perShareTradeCommission $0.02 * -strategy com.zigabyte.stock.strategy.SundayPeaks(0.2,0.08) * -metastock (default path: current directory) * -serialized (default path: current directory) * -serializedgz (default path: current directory) * Values may need to be quoted '$1' or 'pkg.MyStrategy(0.1)'. * Use only one -metastock, -serialized, or -serializedgz to specify data. * </pre> **/ public static void main(String... parameters) { double initialCash = DEFAULT_INITIAL_CASH; double initialPerTradeFee = DEFAULT_PER_TRADE_FEE; double initialPerShareTradeCommission = DEFAULT_PER_SHARE_TRADE_COMMISSION; String initialStrategy = DEFAULT_STRATEGY; String initialDataFormat = DEFAULT_DATA_FORMAT; String initialDataPath = DEFAULT_DATA_PATH; // parse parameters int parameterIndex = 0; try { for (; parameterIndex < parameters.length; parameterIndex++) { String parameter = parameters[parameterIndex]; if ("-initialCash".equalsIgnoreCase(parameter) || "-perTradeFee".equalsIgnoreCase(parameter) || "-perShareTradeCommission".equalsIgnoreCase(parameter)) { double value = DOLLAR_FORMAT.parse(parameters[++parameterIndex]).doubleValue(); if ("-initialCash".equalsIgnoreCase(parameter)) { initialCash = value; } else if ("-perTradeFee".equalsIgnoreCase(parameter)) { initialPerTradeFee = value; } else if ("-perShareTradeCommission".equalsIgnoreCase(parameter)) { initialPerShareTradeCommission = value; } else assert false; } else if ("-strategy".equalsIgnoreCase(parameter) || "-metastock".equalsIgnoreCase(parameter) || "-serialized".equalsIgnoreCase(parameter) || "-serializedgz".equalsIgnoreCase(parameter)) { StringBuffer buf = new StringBuffer(); String part; while (++parameterIndex < parameters.length && !(part = parameters[parameterIndex]).startsWith("-")) { if (buf.length() > 0) buf.append(' '); buf.append(part); } --parameterIndex; String value = buf.toString(); if ("-strategy".equalsIgnoreCase(parameter)) { initialStrategy = value; } else if ("-metastock".equalsIgnoreCase(parameter)) { initialDataPath = value; initialDataFormat = "Metastock"; } else if ("-serialized".equalsIgnoreCase(parameter)) { initialDataPath = value; initialDataFormat = "Serialized"; } else if ("-serializedgz".equalsIgnoreCase(parameter)) { initialDataPath = value; initialDataFormat = "SerializedGZ"; } else assert false; } else if ("-help".equalsIgnoreCase(parameter)) { parameterExit(0); } else throw new IllegalArgumentException(parameter); } } catch (Exception e) { System.err.println(e); int indent = 0; for (int i = 0; i < parameters.length; i++) { String parameter = parameters[i]; if (i < parameterIndex) indent += parameter.length() + 1; System.err.print(parameter); System.err.print(' '); } System.err.println(); for (int i = 0; i < indent; i++) System.err.print('_'); System.err.println('^'); parameterExit(-1); } // set up plotter StrategyPlotter plotter = new StrategyPlotter(initialCash, initialPerTradeFee, initialPerShareTradeCommission, initialStrategy, initialDataFormat, initialDataPath); plotter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); plotter.setSize(1024, 768); plotter.setLocationRelativeTo(null); // center on screen plotter.setVisible(true); }
From source file:CreateTableWithAllDataTypesInMySQL.java
public static void main(String[] args) throws Exception { PreparedStatement pstmt = null; Connection conn = null;/* w w w .j av a 2s. c o m*/ try { StringBuffer sql = new StringBuffer("CREATE TABLE tableWithAllTypes("); sql.append("column_boolean BOOL, "); // boolean sql.append("column_byte TINYINT, "); // byte sql.append("column_short SMALLINT, "); // short sql.append("column_int INTEGER, "); // int sql.append("column_long BIGINT, "); // long sql.append("column_float FLOAT, "); // float sql.append("column_double DOUBLE PRECISION, "); // double sql.append("column_bigdecimal DECIMAL(13,0), "); // BigDecimal sql.append("column_string VARCHAR(254), "); // String sql.append("column_date DATE, "); // Date sql.append("column_time TIME, "); // Time sql.append("column_timestamp TIMESTAMP, "); // Timestamp sql.append("column_asciistream1 TINYTEXT, "); // Clob ( 2^8 bytes) sql.append("column_asciistream2 TEXT, "); // Clob ( 2^16 bytes) sql.append("column_asciistream3 MEDIUMTEXT, "); // Clob (2^24 bytes) sql.append("column_asciistream4 LONGTEXT, "); // Clob ( 2^32 bytes) sql.append("column_blob1 TINYBLOB, "); // Blob ( 2^8 bytes) sql.append("column_blob2 BLOB, "); // Blob ( 2^16 bytes) sql.append("column_blob3 MEDIUMBLOB, "); // Blob ( 2^24 bytes) sql.append("column_blob4 LONGBLOB)"); // Blob ( 2^32 bytes) conn = getConnection(); pstmt = conn.prepareStatement(sql.toString()); pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } }
From source file:CreateTableAllTypesInOracle.java
public static void main(String[] args) { PreparedStatement pstmt = null; Connection conn = null;/*from w w w. j av a2s.com*/ try { conn = getConnection(); pstmt = conn.prepareStatement("CREATE TYPE varray_type is VARRAY(5) OF VARCHAR(10)"); pstmt.executeUpdate(); // Create an OBJECT type pstmt = conn.prepareStatement( "CREATE TYPE oracle_object is OBJECT(column_string VARCHAR(128), column_integer INTEGER)"); pstmt.executeUpdate(); StringBuffer allTypesTable = new StringBuffer("CREATE TABLE oracle_all_types("); // Column Name Oracle Type Java Type allTypesTable.append("column_short SMALLINT, "); // short allTypesTable.append("column_int INTEGER, "); // int allTypesTable.append("column_float REAL, "); // float; can also be NUMBER allTypesTable.append("column_double DOUBLE PRECISION, "); // double; can also be FLOAT or NUMBER allTypesTable.append("column_bigdecimal DECIMAL(13,0), "); // BigDecimal allTypesTable.append("column_string VARCHAR2(254), "); // String; can also be CHAR(n) allTypesTable.append("column_characterstream LONG, "); // CharacterStream or AsciiStream allTypesTable.append("column_bytes RAW(2000), "); // byte[]; can also be LONG RAW(n) allTypesTable.append("column_binarystream RAW(2000), "); // BinaryStream; can also be LONG RAW(n) allTypesTable.append("column_timestamp DATE, "); // Timestamp allTypesTable.append("column_clob CLOB, "); // Clob allTypesTable.append("column_blob BLOB, "); // Blob; can also be BFILE allTypesTable.append("column_bfile BFILE, "); // oracle.sql.BFILE allTypesTable.append("column_array varray_type, "); // oracle.sql.ARRAY allTypesTable.append("column_object oracle_object)"); // oracle.sql.OBJECT pstmt.executeUpdate(allTypesTable.toString()); } catch (Exception e) { // creation of table failed. // handle the exception e.printStackTrace(); } }
From source file:TextVerifyInputFormatDate.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout()); final Text text = new Text(shell, SWT.BORDER); text.setText("YYYY/MM/DD"); ;// w w w . j a v a 2s . c om final Calendar calendar = Calendar.getInstance(); text.addListener(SWT.Verify, new Listener() { boolean ignore; public void handleEvent(Event e) { if (ignore) return; e.doit = false; StringBuffer buffer = new StringBuffer(e.text); char[] chars = new char[buffer.length()]; buffer.getChars(0, chars.length, chars, 0); if (e.character == '\b') { for (int i = e.start; i < e.end; i++) { switch (i) { case 0: /* [Y]YYY */ case 1: /* Y[Y]YY */ case 2: /* YY[Y]Y */ case 3: /* YYY[Y] */ { buffer.append('Y'); break; } case 5: /* [M]M */ case 6: /* M[M] */ { buffer.append('M'); break; } case 8: /* [D]D */ case 9: /* D[D] */ { buffer.append('D'); break; } case 4: /* YYYY[/]MM */ case 7: /* MM[/]DD */ { buffer.append('/'); break; } default: return; } } text.setSelection(e.start, e.start + buffer.length()); ignore = true; text.insert(buffer.toString()); ignore = false; text.setSelection(e.start, e.start); return; } int start = e.start; if (start > 9) return; int index = 0; for (int i = 0; i < chars.length; i++) { if (start + index == 4 || start + index == 7) { if (chars[i] == '/') { index++; continue; } buffer.insert(index++, '/'); } if (chars[i] < '0' || '9' < chars[i]) return; if (start + index == 5 && '1' < chars[i]) return; /* [M]M */ if (start + index == 8 && '3' < chars[i]) return; /* [D]D */ index++; } String newText = buffer.toString(); int length = newText.length(); StringBuffer date = new StringBuffer(text.getText()); date.replace(e.start, e.start + length, newText); calendar.set(Calendar.YEAR, 1901); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DATE, 1); String yyyy = date.substring(0, 4); if (yyyy.indexOf('Y') == -1) { int year = Integer.parseInt(yyyy); calendar.set(Calendar.YEAR, year); } String mm = date.substring(5, 7); if (mm.indexOf('M') == -1) { int month = Integer.parseInt(mm) - 1; int maxMonth = calendar.getActualMaximum(Calendar.MONTH); if (0 > month || month > maxMonth) return; calendar.set(Calendar.MONTH, month); } String dd = date.substring(8, 10); if (dd.indexOf('D') == -1) { int day = Integer.parseInt(dd); int maxDay = calendar.getActualMaximum(Calendar.DATE); if (1 > day || day > maxDay) return; calendar.set(Calendar.DATE, day); } else { if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) { char firstChar = date.charAt(8); if (firstChar != 'D' && '2' < firstChar) return; } } text.setSelection(e.start, e.start + length); ignore = true; text.insert(newText); ignore = false; } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:TextVerifyInputRegularExpression.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout()); final Text text = new Text(shell, SWT.BORDER); Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$ text.setFont(font);/* ww w . j a va 2 s . c om*/ text.setText(template); text.addListener(SWT.Verify, new Listener() { // create the pattern for verification Pattern pattern = Pattern.compile(REGEX); // ignore event when caused by inserting text inside event handler boolean ignore; public void handleEvent(Event e) { if (ignore) return; e.doit = false; if (e.start > 13 || e.end > 14) return; StringBuffer buffer = new StringBuffer(e.text); // handle backspace if (e.character == '\b') { for (int i = e.start; i < e.end; i++) { // skip over separators switch (i) { case 0: if (e.start + 1 == e.end) { return; } else { buffer.append('('); } break; case 4: if (e.start + 1 == e.end) { buffer.append(new char[] { '#', ')' }); e.start--; } else { buffer.append(')'); } break; case 8: if (e.start + 1 == e.end) { buffer.append(new char[] { '#', '-' }); e.start--; } else { buffer.append('-'); } break; default: buffer.append('#'); } } text.setSelection(e.start, e.start + buffer.length()); ignore = true; text.insert(buffer.toString()); ignore = false; // move cursor backwards over separators if (e.start == 5 || e.start == 9) e.start--; text.setSelection(e.start, e.start); return; } StringBuffer newText = new StringBuffer(defaultText); char[] chars = e.text.toCharArray(); int index = e.start - 1; for (int i = 0; i < e.text.length(); i++) { index++; switch (index) { case 0: if (chars[i] == '(') continue; index++; break; case 4: if (chars[i] == ')') continue; index++; break; case 8: if (chars[i] == '-') continue; index++; break; } if (index >= newText.length()) return; newText.setCharAt(index, chars[i]); } // if text is selected, do not paste beyond range of selection if (e.start < e.end && index + 1 != e.end) return; Matcher matcher = pattern.matcher(newText); if (matcher.lookingAt()) { text.setSelection(e.start, index + 1); ignore = true; text.insert(newText.substring(e.start, index + 1)); ignore = false; } } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } font.dispose(); display.dispose(); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildRetrofitLexicons.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_DESC); options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC); options.addOption(OUT_FILE_PARAM, null, true, OUT_FILE_DESC); options.addOption(MIN_PROB_PARAM, null, true, MIN_PROB_DESC); options.addOption(FORMAT_PARAM, null, true, FORMAT_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w. ja v a 2 s . com CommandLine cmd = parser.parse(options, args); String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); int gizaIterQty = -1; if (cmd.hasOption(CommonParams.GIZA_ITER_QTY_PARAM)) { gizaIterQty = Integer.parseInt(cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM)); } else { Usage("Specify: " + CommonParams.GIZA_ITER_QTY_PARAM, options); } String outFileName = cmd.getOptionValue(OUT_FILE_PARAM); if (null == outFileName) { Usage("Specify: " + OUT_FILE_PARAM, options); } String indexDir = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == indexDir) { Usage("Specify: " + CommonParams.MEMINDEX_DESC, options); } FormatType outType = FormatType.kOrig; String outTypeStr = cmd.getOptionValue(FORMAT_PARAM); if (null != outTypeStr) { if (outTypeStr.equals(ORIG_TYPE)) { outType = FormatType.kOrig; } else if (outTypeStr.equals(WEIGHTED_TYPE)) { outType = FormatType.kWeighted; } else if (outTypeStr.equals(UNWEIGHTED_TYPE)) { outType = FormatType.kUnweighted; } else { Usage("Unknown format type: " + outTypeStr, options); } } float minProb = 0; if (cmd.hasOption(MIN_PROB_PARAM)) { minProb = Float.parseFloat(cmd.getOptionValue(MIN_PROB_PARAM)); } else { Usage("Specify: " + MIN_PROB_PARAM, options); } System.out.println(String.format( "Saving lexicon to '%s' (output format '%s'), keep only entries with translation probability >= %f", outFileName, outType.toString(), minProb)); // We use unlemmatized text here, because lemmatized dictionary is going to be mostly subset of the unlemmatized one. InMemForwardIndex textIndex = new InMemForwardIndex(FeatureExtractor.indexFileName(indexDir, FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID])); InMemForwardIndexFilterAndRecoder filterAndRecoder = new InMemForwardIndexFilterAndRecoder(textIndex); String prefix = gizaRootDir + "/" + FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID] + "/"; GizaVocabularyReader answVoc = new GizaVocabularyReader(prefix + "source.vcb", filterAndRecoder); GizaVocabularyReader questVoc = new GizaVocabularyReader(prefix + "target.vcb", filterAndRecoder); GizaTranTableReaderAndRecoder gizaTable = new GizaTranTableReaderAndRecoder(false, // we don't need to flip the table for the purpose prefix + "/output.t1." + gizaIterQty, filterAndRecoder, answVoc, questVoc, (float) FeatureExtractor.DEFAULT_PROB_SELF_TRAN, minProb); BufferedWriter outFile = new BufferedWriter(new FileWriter(outFileName)); for (int srcWordId = 0; srcWordId <= textIndex.getMaxWordId(); ++srcWordId) { GizaOneWordTranRecs tranRecs = gizaTable.getTranProbs(srcWordId); if (null != tranRecs) { String wordSrc = textIndex.getWord(srcWordId); StringBuffer sb = new StringBuffer(); sb.append(wordSrc); for (int k = 0; k < tranRecs.mDstIds.length; ++k) { float prob = tranRecs.mProbs[k]; if (prob >= minProb) { int dstWordId = tranRecs.mDstIds[k]; if (dstWordId == srcWordId && outType != FormatType.kWeighted) continue; // Don't duplicate the word, unless it's probability weighted sb.append(' '); String dstWord = textIndex.getWord(dstWordId); if (null == dstWord) { throw new Exception( "Bug or inconsistent data: Couldn't retriev a word for wordId = " + dstWordId); } if (dstWord.indexOf(':') >= 0) throw new Exception( "Illegal dictionary word '" + dstWord + "' b/c it contains ':'"); sb.append(dstWord); if (outType != FormatType.kOrig) { sb.append(':'); sb.append(outType == FormatType.kWeighted ? prob : 1); } } } outFile.write(sb.toString()); outFile.newLine(); } } outFile.close(); } catch (ParseException e) { e.printStackTrace(); Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } System.out.println("Terminated successfully!"); }
From source file:com.netcrest.pado.tools.pado.PadoShell.java
/** * @param args/*from w ww . j a v a 2 s.c om*/ * @throws Exception */ public static void main(String[] args) throws Exception { PadoShell padoShell = new PadoShell(args); if (padoShell.isInteractiveMode()) { padoShell.initSignals(); padoShell.go(); } else { padoShell.setShowTime(false); if (padoShell.inputCommands != null) { StringBuffer buffer = new StringBuffer(padoShell.inputCommands.length * 10); for (String value : padoShell.inputCommands) { buffer.append(value + " "); } String parsedCommands[] = buffer.toString().split(";"); for (String command : parsedCommands) { padoShell.runCommand(command, false); } } if (padoShell.scriptFilePath != null) { File file = new File(padoShell.scriptFilePath); if (file.exists() == false) { printlnError(padoShell.scriptFilePath + ": File does not exist."); System.exit(-1); } padoShell.runScript(file); } padoShell.waitForBackgroundToComplete(); SharedCache.getSharedCache().disconnect(); System.exit(0); } }
From source file:com.adito.server.Main.java
/** * Entry point/*www. ja v a2 s . com*/ * * @param args * @throws Throwable */ public static void main(String[] args) throws Throwable { // This is a hack to allow the Install4J installer to get the java // runtime that will be used if (args.length > 0 && args[0].equals("--jvmdir")) { System.out.println(SystemProperties.get("java.home")); System.exit(0); } useWrapper = System.getProperty("wrapper.key") != null; final Main main = new Main(); ContextHolder.setContext(main); if (useWrapper) { WrapperManager.start(main, args); } else { Integer returnCode = main.start(args); if (returnCode != null) { if (main.gui) { if (main.startupException == null) { main.startupException = new Exception("An exit code of " + returnCode + " was returned."); } try { if (SystemProperties.get("os.name").toLowerCase().startsWith("windows")) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } } catch (Exception e) { } String mesg = main.startupException.getMessage() == null ? "No message supplied." : main.startupException.getMessage(); StringBuffer buf = new StringBuffer(); int l = 0; char ch = ' '; for (int i = 0; i < mesg.length(); i++) { ch = mesg.charAt(i); if (l > 50 && ch == ' ') { buf.append("\n"); l = 0; } else { if (ch == '\n') { l = 0; } else { l++; } buf.append(ch); } } mesg = buf.toString(); final String fMesg = mesg; SwingUtilities.invokeAndWait(new Runnable() { public void run() { JOptionPane.showMessageDialog(null, fMesg, "Startup Error", JOptionPane.ERROR_MESSAGE); } }); } System.exit(returnCode.intValue()); } else { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (!main.shuttingDown) { main.stop(0); } } }); } } }
From source file:bamboo.openhash.fileshare.FileShare.java
public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); // create Options object Options options = new Options(); // add t option options.addOption("r", "read", false, "read a file from the DHT"); options.addOption("w", "write", false, "write a file to the DHT"); options.addOption("g", "gateway", true, "the gateway IP:port"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String gw = null;//from ww w . ja va 2 s.c o m String mode = null; String secret = null; String ttl = null; String key = null; String file = null; if (cmd.hasOption("r")) { mode = "read"; } if (cmd.hasOption("w")) { mode = "write"; } if (cmd.hasOption("g")) { gw = cmd.getOptionValue("g"); } if (cmd.hasOption("k")) { key = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secret = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = cmd.getOptionValue("t"); } if (mode == null) { System.err.println("ERROR: either --read or --write is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } if (gw == null) { System.err.println("ERROR: --gateway is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } if (secret == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } StringBuffer sbuf = new StringBuffer(1000); sbuf.append("<sandstorm>\n"); sbuf.append("<global>\n"); sbuf.append("<initargs>\n"); sbuf.append("node_id localhost:3630\n"); sbuf.append("</initargs>\n"); sbuf.append("</global>\n"); sbuf.append("<stages>\n"); sbuf.append("<GatewayClient>\n"); sbuf.append("class bamboo.dht.GatewayClient\n"); sbuf.append("<initargs>\n"); sbuf.append("debug_level 0\n"); sbuf.append("gateway " + gw + "\n"); sbuf.append("</initargs>\n"); sbuf.append("</GatewayClient>\n"); sbuf.append("\n"); sbuf.append("<FileShare>\n"); sbuf.append("class bamboo.openhash.fileshare.FileShare\n"); sbuf.append("<initargs>\n"); sbuf.append("debug_level 0\n"); sbuf.append("secret " + secret + "\n"); sbuf.append("mode " + mode + "\n"); if (mode.equals("write")) { if (ttl == null) { System.err.println("ERROR: --ttl is required for write mode"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } sbuf.append("ttl " + ttl + "\n"); sbuf.append("file " + file + "\n"); } else { if (key == null) { System.err.println("ERROR: --key is required for write mode"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } sbuf.append("key " + key + "\n"); sbuf.append("file " + file + "\n"); } sbuf.append("client_stage_name GatewayClient\n"); sbuf.append("</initargs>\n"); sbuf.append("</FileShare>\n"); sbuf.append("</stages>\n"); sbuf.append("</sandstorm>\n"); ASyncCore acore = new bamboo.lss.ASyncCoreImpl(); DustDevil dd = new DustDevil(); dd.set_acore_instance(acore); dd.main(new CharArrayReader(sbuf.toString().toCharArray())); acore.async_main(); }