List of usage examples for java.io File delete
public boolean delete()
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java
public static void main(String[] args) throws Exception { // input dir - list of xml query containers // step5-linguistic-annotation/ System.err.println("Starting step 6 HIT Preparation"); File inputDir = new File(args[0]); // output dir File outputDir = new File(args[1]); if (outputDir.exists()) { outputDir.delete(); }// w ww . j av a2 s. co m outputDir.mkdir(); List<String> queries = new ArrayList<>(); // iterate over query containers int countClueWeb = 0; int countSentence = 0; for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) { QueryResultContainer queryResultContainer = QueryResultContainer .fromXML(FileUtils.readFileToString(f, "utf-8")); if (queries.contains(f.getName()) || queries.size() == 0) { // groups contain only non-empty documents Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>(); // split to groups according to number of sentences for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) { if (rankedResult.originalXmi != null) { byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class); int groupId = sentences.size() / 40; if (rankedResult.originalXmi == null) { System.err.println("Empty document: " + rankedResult.clueWebID); } else { if (!groups.containsKey(groupId)) { groups.put(groupId, new ArrayList<>()); } } //handle it groups.get(groupId).add(rankedResult); countClueWeb++; } } for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) { Integer groupId = entry.getKey(); List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue(); // make sure the results are sorted // DEBUG // for (QueryResultContainer.SingleRankedResult r : rankedResults) { // System.out.print(r.rank + "\t"); // } Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank)); // iterate over results for one query and group for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) { QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i); QueryResultContainer.SingleRankedResult r = rankedResults.get(i); int rank = r.rank; MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile("template/template.html"); String queryId = queryResultContainer.qID; String query = queryResultContainer.query; // make the first letter uppercase query = query.substring(0, 1).toUpperCase() + query.substring(1); List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples; List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples; byte[] bytes = new BASE64Decoder() .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes())); JCas jCas = JCasFactory.createJCas(); XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas()); List<generators.Sentence> sentences = new ArrayList<>(); List<Integer> paragraphs = new ArrayList<>(); paragraphs.add(0); for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) { for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) { String sentenceBegin = String.valueOf(s.getBegin()); generators.Sentence sentence = new generators.Sentence(s.getCoveredText(), sentenceBegin); sentences.add(sentence); countSentence++; } int SentenceID = paragraphs.get(paragraphs.size() - 1); if (sentences.size() > 120) while (SentenceID < sentences.size()) { if (!paragraphs.contains(SentenceID)) paragraphs.add(SentenceID); SentenceID = SentenceID + 120; } paragraphs.add(sentences.size()); } System.err.println("Output dir: " + outputDir); int startID = 0; int endID; for (int j = 0; j < paragraphs.size(); j++) { endID = paragraphs.get(j); int sentLength = endID - startID; if (sentLength > 120 || j == paragraphs.size() - 1) { if (sentLength > 120) { endID = paragraphs.get(j - 1); j--; } sentLength = endID - startID; if (sentLength <= 40) groupId = 40; else if (sentLength <= 80 && sentLength > 40) groupId = 80; else if (sentLength > 80) groupId = 120; File folder = new File(outputDir + "/" + groupId); if (!folder.exists()) { System.err.println("creating directory: " + outputDir + "/" + groupId); boolean result = false; try { folder.mkdir(); result = true; } catch (SecurityException se) { //handle it } if (result) { System.out.println("DIR created"); } } String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + ".html"; System.err.println("Printing a file: " + newHtmlFile); File newHTML = new File(newHtmlFile); int t = 0; while (newHTML.exists()) { newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_" + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html"); t++; } mustache.execute(new PrintWriter(new FileWriter(newHTML)), new generators(query, relevantInformationExamples, irrelevantInformationExamples, sentences.subList(startID, endID), queryId, rank)) .flush(); startID = endID; } } } } } } System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences"); }
From source file:net.sf.ginp.TestGinpModel.java
/** * Description of the Method//from w w w. j a v a 2s. com * *@param args Description of the Parameter */ public static void main(String[] args) { junit.textui.TestRunner.run(TestGinpModel.class); File fl = new File(CONFIG_FILE_LOCATION); fl.delete(); }
From source file:ProductionJS.java
/** * @param args/*from w w w. j ava2s. c om*/ */ public static void main(String[] args) { boolean precondition = true; BackupLog backupLog = new BackupLog("log/backupLog.txt"); Property properties = null; Settings settings = null; // Load main cfg file try { properties = new Property("cfg/cfg"); } catch (IOException e) { backupLog.log("ERROR : Config file not found"); precondition = false; } // Load cfg for Log4J if (precondition) { try { DOMConfigurator.configureAndWatch(properties.getProperty("loggerConfiguration")); logger.info("ProductionJS is launched\n_______________________"); } catch (Exception e) { backupLog.log(e.getMessage()); precondition = false; } } // Load settings for current execution if (precondition) { try { settings = new Settings(new File(properties.getProperty("importConfiguration"))); } catch (IOException e) { logger.error("Properties file not found"); precondition = false; } catch (org.json.simple.parser.ParseException e) { logger.error("Properties file reading error : JSON may be invalid, check it!"); precondition = false; } } // All is OK : GO! if (precondition) { logger.info("Configuration OK"); logger.info("\"_______________________\nConcat BEGIN\n_______________________\n"); Concat concat = new Concat(); try { if (settings.getPrior() != null) { logger.info("Add Prior files\n_______________________\n"); concat.addJSONArray(settings.getPrior()); } for (int i = 0; i < settings.getIn().size(); i++) { ProductionJS.logger.info("Importation number " + (i + 1)); ProductionJS.logger.info("Directory imported " + settings.getIn().get(i)); Directory dir = new Directory(new File(settings.getIn().get(i).toString())); dir.scan(); concat.add(dir.getFiles()); } concat.output(settings.getOut()); logger.info("\"_______________________\nConcat END\n_______________________\n"); if (settings.getMinify() != null && settings.getMinify() == true) { logger.info( "\"_______________________\nMinify of concatened file BEGIN\n_______________________\n"); new Minify(new File(settings.getOut()), settings.getOut()); logger.info( "\"_______________________\nMinify of concatened file END\n_______________________\n"); } if (settings.getLicense() != null) { logger.info("Add License\n_______________________\n"); concat = new Concat(); UUID uniqueID = UUID.randomUUID(); PrintWriter tmp = new PrintWriter(uniqueID.toString() + ".txt"); tmp.println(settings.getLicense()); tmp.close(); File license = new File(uniqueID.toString() + ".txt"); concat.add(license); File out = new File(settings.getOut()); File tmpOut = new File(uniqueID + out.getName()); out.renameTo(tmpOut); concat.add(tmpOut); concat.output(settings.getOut()); license.delete(); tmpOut.delete(); } } catch (IOException e) { StackTrace stackTrace = new StackTrace(e.getStackTrace()); logger.error("An error occurred " + e.getMessage() + " " + stackTrace.toString()); } } }
From source file:com.tvh.gmaildrafter.Drafter.java
/** * @param args the command line arguments *//* www . j a v a2 s. c om*/ public static void main(String[] args) { Options options = getCMDLineOptions(); CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelpMessage(options); System.exit(0); } String emailBody = null; String emailSubject = null; if (cmd.hasOption("body")) { String bodyFile = cmd.getOptionValue("body"); File body = new File(bodyFile); emailBody = FileUtils.readFileToString(body); if (cmd.hasOption("deletebody")) { body.delete(); } } else if (cmd.hasOption("stdin")) { emailBody = Util.readEntireStdin(); } if (cmd.hasOption("subject")) emailSubject = cmd.getOptionValue("subject"); else if (cmd.hasOption("subjectfile")) { String subjectFile = cmd.getOptionValue("subjectfile"); File subject = new File(subjectFile); emailSubject = FileUtils.readFileToString(subject); if (cmd.hasOption("deletesubjectfile")) subject.delete(); } String username = null; if (cmd.hasOption("username")) username = cmd.getOptionValue("username"); String password = null; if (cmd.hasOption("password")) password = cmd.getOptionValue("password"); String[] bcc = cmd.getOptionValues("bcc"); String[] cc = cmd.getOptionValues("cc"); Boolean sendImmediately = cmd.hasOption("immediate"); String[] attachments = cmd.getOptionValues("attachments"); String[] attachmentnames = cmd.getOptionValues("attachmentnames"); String[] destinations = cmd.getOptionValues("to"); Credentials credentials = Authenticater.getValidCredentials(username, password); if (credentials != null) { boolean success = false; while (!success) { try { composeMail(credentials, emailSubject, emailBody, attachments, attachmentnames, destinations, cc, bcc, sendImmediately); success = true; } catch (AuthenticationFailedException e) { JOptionPane.showMessageDialog(null, "Invalid login, please try again!"); credentials = Authenticater.getValidCredentials(username, null); success = false; } } } } catch (ParseException ex) { javax.swing.JOptionPane.showMessageDialog(null, ex.getMessage()); printHelpMessage(options); System.exit(7); } catch (IOException ex) { System.out.println("IO Exception " + ex.getLocalizedMessage()); printHelpMessage(options); System.exit(2); } catch (LoginException ex) { System.out.println(ex.getMessage()); System.exit(3); } System.exit(0); }
From source file:etomica.virial.MCMoveClusterRingRegrowOrientation.java
public static void main(String[] args) { ISpace space = Space3D.getInstance(); ClusterWeight cluster = new ClusterWeight() { @Override// www.ja v a2 s .c o m public double value(BoxCluster box) { // TODO Auto-generated method stub return 1; } @Override public void setTemperature(double temperature) { // TODO Auto-generated method stub } @Override public int pointCount() { // TODO Auto-generated method stub return 1; } @Override public ClusterAbstract makeCopy() { // TODO Auto-generated method stub return null; } }; BoxCluster box = new BoxCluster(cluster, space); Simulation sim = new Simulation(space); sim.addBox(box); IAtomTypeOriented atype = new AtomTypeOrientedSphere(Hydrogen.INSTANCE, space); SpeciesSpheresHetero species = new SpeciesSpheresHetero(space, new IAtomTypeOriented[] { atype }); sim.addSpecies(species); File file1 = new File("acceptance.dat"); if (file1.exists()) { file1.delete(); } for (int p = 2; p <= 512; p *= 2) { box.setNMolecules(species, 0); species.setChildCount(new int[] { p }); box.setNMolecules(species, 1); IntegratorMC integrator = new IntegratorMC(sim, null); integrator.setBox(box); MCMoveClusterRingRegrowOrientation move = new MCMoveClusterRingRegrowOrientation(sim.getRandom(), space, p); for (int iTemp = 40; iTemp <= 40; iTemp += 2) { move.foo = 0; move.setStiffness(Kelvin.UNIT.toSim(iTemp), species.getAtomType(0).getMass()); integrator.getMoveManager().addMCMove(move); integrator.reset(); int total = 100; for (int i = 0; i < total; i++) { integrator.doStep(); } try { FileWriter Temp = new FileWriter("acceptance.dat", true); Temp.write( iTemp + " " + p + " " + move.getStiffness() + " " + ((double) move.foo) / total + "\n"); Temp.close(); } catch (IOException ex1) { throw new RuntimeException(ex1); } System.out.println( "p = " + p + " ,Temp = " + iTemp + " ,acceptance ratio = " + ((double) move.foo) / total); } } }
From source file:android.example.hlsmerge.crypto.Main.java
public static void main(String[] args) { CommandLine commandLine = parseCommandLine(args); String[] commandLineArgs = commandLine.getArgs(); try {//from ww w . j ava2 s. c o m String playlistUrl = commandLineArgs[0]; String outFile = null; String key = null; if (commandLine.hasOption(OPT_OUT_FILE)) { outFile = commandLine.getOptionValue(OPT_OUT_FILE); File file = new File(outFile); if (file.exists()) { if (!commandLine.hasOption(OPT_OVERWRITE)) { System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile); int ch = System.in.read(); if (!(ch == 'y' || ch == 'Y')) { System.exit(0); } } file.delete(); } } if (commandLine.hasOption(OPT_KEY)) key = commandLine.getOptionValue(OPT_KEY); PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl, null); if (commandLine.hasOption(OPT_SILENT)) { System.setOut(new PrintStream(new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } })); } downloader.download(outFile, key); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:net.chrislongo.hls.Main.java
public static void main(String[] args) { CommandLine commandLine = parseCommandLine(args); String[] commandLineArgs = commandLine.getArgs(); try {/* w w w . jav a 2 s . c om*/ String playlistUrl = commandLineArgs[0]; String outFile = null; String key = null; if (commandLine.hasOption(OPT_OUT_FILE)) { outFile = commandLine.getOptionValue(OPT_OUT_FILE); File file = new File(outFile); if (file.exists()) { if (!commandLine.hasOption(OPT_OVERWRITE)) { System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile); int ch = System.in.read(); if (!(ch == 'y' || ch == 'Y')) { System.exit(0); } } file.delete(); } } if (commandLine.hasOption(OPT_KEY)) key = commandLine.getOptionValue(OPT_KEY); PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl); if (commandLine.hasOption(OPT_SILENT)) { System.setOut(new PrintStream(new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } })); } downloader.download(outFile, key); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:com.appeligo.responsetest.ServerResponseChecker.java
/** * @param args// www .j av a 2 s . com */ public static void main(String[] args) { PatternLayout pattern = new PatternLayout("%d{ISO8601} %-5p [%-c{1} - %t] - %m%n"); ConsoleAppender consoleAppender = new ConsoleAppender(pattern); LevelRangeFilter infoFilter = new LevelRangeFilter(); infoFilter.setLevelMin(Level.INFO); consoleAppender.addFilter(infoFilter); BasicConfigurator.configure(consoleAppender); String configFile = "/etc/flip.tv/responsetest.xml"; if (args.length > 0) { if (args.length == 2 && args[0].equals("-config")) { configFile = args[1]; } else { log.error("Usage: java " + ServerResponseChecker.class.getName() + " [-config <xmlfile>]"); System.exit(1); } } try { XMLConfiguration config = new XMLConfiguration(configFile); logFile = config.getString("logFile", logFile); servlet = config.getString("servlet", servlet); timeoutSeconds = config.getLong("timeoutSeconds", timeoutSeconds); responseTimeThresholdSeconds = config.getLong("responseTimeThresholdSeconds", responseTimeThresholdSeconds); reporter = config.getString("reporter", reporter); smtpServer = config.getString("smtpServer", smtpServer); smtpUsername = config.getString("smtpUsername", smtpUsername); smtpPassword = config.getString("smtpPassword", smtpPassword); smtpDebug = config.getBoolean("smtpDebug", smtpDebug); mailTo = config.getString("mailTo", mailTo); } catch (ConfigurationException e) { e.printStackTrace(); } marker = logFile + ".mailed"; try { BasicConfigurator.configure(new RollingFileAppender(pattern, logFile, true)); } catch (IOException e1) { e1.printStackTrace(); } // Add email appender SMTPAppender mailme = new SMTPAppender(); LevelRangeFilter warnFilter = new LevelRangeFilter(); warnFilter.setLevelMin(Level.WARN); mailme.addFilter(warnFilter); mailme.setSMTPDebug(smtpDebug); mailme.setSMTPHost(smtpServer); mailme.setTo(mailTo); mailme.setFrom(reporter + " <" + smtpUsername + ">"); mailme.setBufferSize(1); mailme.setSubject(servlet + " Not Responding!"); mailme.setSMTPUsername(smtpUsername); mailme.setSMTPPassword(smtpPassword); mailme.setLayout(new SimpleLayout()); mailme.activateOptions(); mailme.setLayout(pattern); BasicConfigurator.configure(mailme); long before; ConnectionThread connectionThread = new ConnectionThread(); connectionThread.start(); synchronized (connectionThread) { connectionThread.setOkToGo(true); connectionThread.notifyAll(); before = System.currentTimeMillis(); long delay = timeoutSeconds * 1000; while (!done && delay > 0) { try { connectionThread.wait(delay); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } delay -= (System.currentTimeMillis() - before); } } long after = System.currentTimeMillis(); responseMillis = after - before; String reportStatus = "Could not report"; try { StringBuilder sb = new StringBuilder(); sb.append(servlet + "/responsetest/report.action"); sb.append("?reporter=" + URLEncoder.encode(reporter)); sb.append("&status=" + URLEncoder.encode(status)); sb.append("&bytesRead=" + bytesRead); sb.append("&timedOut=" + (!done)); if (throwable == null) { sb.append("&exception=none"); } else { sb.append("&exception=" + URLEncoder.encode(throwable.getClass().getName() + "-" + throwable.getMessage())); } sb.append("&responseMillis=" + responseMillis); URL reportURL = new URL(sb.toString()); connection = (HttpURLConnection) reportURL.openConnection(); connection.connect(); reportStatus = connection.getResponseCode() + " - " + connection.getResponseMessage(); } catch (Throwable t) { reportStatus = t.getClass().getName() + "-" + t.getMessage(); } StringBuilder sb = new StringBuilder(); sb.append(servlet + ": "); sb.append(status + ", " + bytesRead + " bytes, "); if (done) { sb.append("DONE, "); } else { sb.append("TIMED OUT, "); } sb.append(responseMillis + " millisecond response, "); sb.append(" report status=" + reportStatus); File markerFile = new File(marker); if (done && status.startsWith("200") && (throwable == null)) { if ((responseMillis / 1000) < responseTimeThresholdSeconds) { if (markerFile.exists()) { markerFile.delete(); } log.debug(sb.toString()); } else { if (markerFile.exists()) { log.info(sb.toString()); } else { try { new FileOutputStream(marker).close(); log.warn(sb.toString()); } catch (IOException e) { log.info(sb.toString()); log.info("Can't send email alert because could not write marker file: " + marker + ". " + e.getMessage()); } } } } else { if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); sb.append(sw.toString()); } if (markerFile.exists()) { log.info(sb.toString()); } else { try { new FileOutputStream(marker).close(); log.fatal(sb.toString()); // chosen appender layout ignoresThrowable() } catch (IOException e) { log.info(sb.toString()); log.info("Can't send email alert because could not write marker file: " + marker + ". " + e.getMessage()); } } } }
From source file:com.zimbra.cs.db.SQLite.java
public static void main(String args[]) { // command line argument parsing Options options = new Options(); CommandLine cl = Versions.parseCmdlineArgs(args, options); String outputDir = cl.getOptionValue("o"); File outFile = new File(outputDir, "versions-init.sql"); outFile.delete(); try {// w ww.ja va 2s . c o m String redoVer = com.zimbra.cs.redolog.Version.latest().toString(); String outStr = "-- AUTO-GENERATED .SQL FILE - Generated by the SQLite versions tool\n" + "INSERT INTO config(name, value, description) VALUES\n" + "\t('db.version', '" + Versions.DB_VERSION + "', 'db schema version');\n" + "INSERT INTO config(name, value, description) VALUES\n" + "\t('index.version', '" + Versions.INDEX_VERSION + "', 'index version');\n" + "INSERT INTO config(name, value, description) VALUES\n" + "\t('redolog.version', '" + redoVer + "', 'redolog version');\n"; Writer output = new BufferedWriter(new FileWriter(outFile)); output.write(outStr); output.close(); } catch (IOException e) { System.out.println("ERROR - caught exception at\n"); e.printStackTrace(); System.exit(-1); } }
From source file:com.github.chrbayer84.keybits.KeyBits.java
/** * @param args//from ww w. j a v a 2 s .co m */ public static void main(String[] args) throws Exception { int number_of_addresses = 1; int depth = 1; String usage = "java -jar KeyBits.jar [options]"; // create parameters which can be chosen Option help = new Option("h", "print this message"); Option verbose = new Option("v", "verbose"); Option exprt = new Option("e", "export public key to blockchain"); Option imprt = OptionBuilder.withArgName("string").hasArg() .withDescription("import public key from blockchain").create("i"); Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address") .create("a"); Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet") .create("c"); Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet") .create("u"); Option balance_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("return balance of wallet").create("b"); Option show_wallet = OptionBuilder.withArgName("file name").hasArg() .withDescription("show content of wallet").create("w"); Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis") .create("s"); Option monitor_pending = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor pending transactions of wallet").create("p"); Option monitor_depth = OptionBuilder.withArgName("file name").hasArg() .withDescription("monitor transaction depths of wallet").create("d"); Option number = OptionBuilder.withArgName("integer").hasArg() .withDescription("in combination with -c, -d, -r or -s").create("n"); Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r"); Options options = new Options(); options.addOption(help); options.addOption(verbose); options.addOption(imprt); options.addOption(exprt); options.addOption(blockchain_address); options.addOption(create_wallet); options.addOption(update_wallet); options.addOption(balance_wallet); options.addOption(show_wallet); options.addOption(send_coins); options.addOption(monitor_pending); options.addOption(monitor_depth); options.addOption(number); options.addOption(reset); BasicParser parser = new BasicParser(); CommandLine cmd = null; String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator"); // show help if wrong usage try { cmd = parser.parse(options, args); } catch (Exception e) { printHelp(usage, options, header); } if (cmd.getOptions().length == 0) printHelp(usage, options, header); if (cmd.hasOption("h")) printHelp(usage, options, header); if (cmd.hasOption("v")) System.out.println(header); if (cmd.hasOption("c") && cmd.hasOption("n")) number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue(); if (cmd.hasOption("d") && cmd.hasOption("n")) depth = new Integer(cmd.getOptionValue("n")).intValue(); String checkpoints_file_name = "checkpoints"; if (!new File(checkpoints_file_name).exists()) checkpoints_file_name = null; // --------------------------------------------------------------------- if (cmd.hasOption("c")) { String wallet_file_name = cmd.getOptionValue("c"); String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); if (!new File(wallet_file_name).exists()) { String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name); if (!passphrase.equals(passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase); System.exit(0); } if (cmd.hasOption("u")) { String wallet_file_name = cmd.getOptionValue("u"); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("b")) { String wallet_file_name = cmd.getOptionValue("b"); System.out.println( MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue()); System.exit(0); } if (cmd.hasOption("w")) { String wallet_file_name = cmd.getOptionValue("w"); System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain")); System.exit(0); } if (cmd.hasOption("p")) { System.out.println("monitoring of pending transactions ... "); String wallet_file_name = cmd.getOptionValue("p"); MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("d")) { System.out.println("monitoring of transaction depth ... "); String wallet_file_name = cmd.getOptionValue("d"); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, depth); System.exit(0); } if (cmd.hasOption("r") && cmd.hasOption("n")) { long epoch = new Long(cmd.getOptionValue("n")); System.out.println("resetting wallet ... "); String wallet_file_name = cmd.getOptionValue("r"); File chain_file = (new File(wallet_file_name + ".chain")); if (chain_file.exists()) chain_file.delete(); MyWallet.setCreationTime(wallet_file_name, epoch); MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name); System.exit(0); } if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) { String wallet_file_name = cmd.getOptionValue("s"); String address = cmd.getOptionValue("a"); Integer amount = new Integer(cmd.getOptionValue("n")); String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name); MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address, new BigInteger(amount + ""), wallet_passphrase); System.out.println("waiting ..."); Thread.sleep(10000); System.out.println("monitoring of transaction depth ... "); MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, 1); System.out.println("transaction fixed in blockchain with depth " + depth); System.exit(0); } // ---------------------------------------------------------------------------------------- // creates public key // ---------------------------------------------------------------------------------------- GnuPGP gpg = new GnuPGP(); if (cmd.hasOption("e")) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = input.readLine()) != null) sb.append(line + "\n"); PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString()); //System.out.println(gpg.showPublicKeys(public_key_ring)); byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring); String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded); // System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses)))); // file names for message String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet"; String public_key_wallet_file_name = public_key_file_name; String public_key_chain_file_name = public_key_wallet_file_name + ".chain"; // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage String public_key_wallet_passphrase = HelpfulStuff .insertPassphrase("enter password for " + public_key_wallet_file_name); if (!new File(public_key_wallet_file_name).exists()) { String public_key_wallet_passphrase_ = HelpfulStuff .reInsertPassphrase("enter password for " + public_key_wallet_file_name); if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) { System.out.println("passwords do not match"); System.exit(0); } } MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1, public_key_wallet_passphrase); MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name); String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name, 0); System.out.println("address of public key: " + public_key_address); // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name, addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase); } if (cmd.hasOption("i")) { String location = cmd.getOptionValue("i"); String[] addresses = null; if (location.indexOf(",") > -1) { String[] locations = location.split(","); addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain", checkpoints_file_name, locations[0], locations[1]); } else { addresses = BlockchainDotInfo.getKeys(location); } byte[] encoded = (new Encoding()).decodePublicKey(addresses); PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded); System.out.println(gpg.getArmored(public_key_ring)); System.exit(0); } }