List of usage examples for java.lang String format
public static String format(Locale l, String format, Object... args)
From source file:j8583.example.Server.java
public static void main(String[] args) throws Exception { mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml"); System.err.println("Setting up server socket..."); ServerSocket server = new ServerSocket(9999); System.err.println("Waiting for connections..."); while (true) { Socket sock = server.accept(); System.err.println(String.format("New connection from %s:%d", sock.getInetAddress(), sock.getPort())); new Thread(new Server(sock), "j8583-server").start(); }/* w w w . j a v a 2 s . c om*/ }
From source file:org.excalibur.benchmark.test.EC2InstancesBenchmark.java
public static void main(String[] args) throws IOException { final String benchmark = "sp"; final String outputDir = "/home/alessandro/excalibur/source/services/benchmarks/ec2/"; final String[] scripts = { readLines(getDefaultClassLoader() .getResourceAsStream("org/excalibur/service/deployment/resource/script/iperf3.sh")), readLines(getDefaultClassLoader() .getResourceAsStream("org/excalibur/service/deployment/resource/script/linkpack.sh")), readLines(getDefaultClassLoader().getResourceAsStream( "org/excalibur/service/deployment/resource/script/benchmarks/run_linpack_xeon64.sh")), }; final String[] instanceTypes = { "c3.8xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "i2.xlarge" }; final String privateKeyMaterial = IOUtils2 .readLines(new File(SystemUtils2.getUserDirectory(), "/.ec2/leite.pem")); final File sshKey = new File(SystemUtils2.getUserDirectory(), "/.ec2/leite.pem"); Properties properties = Properties2 .load(getDefaultClassLoader().getResourceAsStream("aws-config.properties")); final LoginCredentials loginCredentials = new LoginCredentials.Builder() .identity(properties.getProperty("aws.access.key")) .credential(properties.getProperty("aws.secret.key")).credentialName("leite").build(); final UserProviderCredentials userProviderCredentials = new UserProviderCredentials() .setLoginCredentials(loginCredentials) .setRegion(new Region("us-east-1").setEndpoint("https://ec2.us-east-1.amazonaws.com")); final EC2 ec2 = new EC2(userProviderCredentials); List<Callable<Void>> tasks = Lists.newArrayList(); for (final String instanceType : instanceTypes) { tasks.add(new Callable<Void>() { @Override/*from w w w . j ava2 s.c om*/ public Void call() throws Exception { InstanceTemplate template = new InstanceTemplate().setImageId("ami-864d84ee") .setInstanceType(InstanceType.valueOf(instanceType)).setKeyName("leite") .setLoginCredentials( loginCredentials.toBuilder().privateKey(privateKeyMaterial).build()) .setGroup(new org.excalibur.core.cloud.api.Placement().setZone("us-east-1a")) //.setGroupName("iperf-bench") .setMinCount(1).setMaxCount(1) .setInstanceName(String.format("%s-%s", instanceType, benchmark)) .setRegion(userProviderCredentials.getRegion()).setTags(Tags .newTags(new org.excalibur.core.cloud.api.domain.Tag("benchmark", benchmark))); final Instances instances = ec2.createInstances(template); for (VirtualMachine instance : instances) { Preconditions.checkState( !Strings.isNullOrEmpty(instance.getConfiguration().getPlatformUserName())); Preconditions.checkState( !Strings.isNullOrEmpty(instance.getConfiguration().getPublicIpAddress())); HostAndPort hostAndPort = fromParts(instance.getConfiguration().getPublicIpAddress(), 22); LoginCredentials sshCredentials = new LoginCredentials.Builder().authenticateAsSudo(true) .privateKey(sshKey).user(instance.getConfiguration().getPlatformUserName()).build(); SshClient client = SshClientFactory.defaultSshClientFactory().create(hostAndPort, sshCredentials); client.connect(); try { for (int i = 0; i < scripts.length; i++) { ExecutableResponse response = client.execute(scripts[i]); Files.write(response.getOutput().getBytes(), new File(outputDir, String.format("%s-%s.output.txt", template.getInstanceName(), i))); LOG.info( "Executed the script [{}] with exit code [{}], error [{}], and output [{}] ", new Object[] { scripts[i], String.valueOf(response.getExitStatus()), response.getError(), response.getOutput() }); } } finally { client.disconnect(); } ec2.terminateInstance(instance); } return null; } }); } ListeningExecutorService executor = DynamicExecutors .newListeningDynamicScalingThreadPool("benchmark-instances-thread-%d"); Futures2.invokeAllAndShutdownWhenFinish(tasks, executor); ec2.close(); }
From source file:eu.cognitum.readandwrite.App.java
public static void main(String[] args) { try {/*www .j av a2s. c o m*/ String configFile = 0 == args.length ? "example.properties" : args[0]; CONFIGURATION = new Properties(); File f = new File(configFile); if (!f.exists()) { LOGGER.warning("configuration not found at " + configFile); return; } LOGGER.info("loading configuration file " + f.getAbsoluteFile()); CONFIGURATION.load(new FileInputStream(f)); String ip = CONFIGURATION.getProperty(PROP_STORAGE_HOSTNAME); String keyspace = CONFIGURATION.getProperty(PROP_STORAGE_KEYSPACE); String directory = CONFIGURATION.getProperty(PROP_STORAGE_DIRECTORY); // N of articles to be generated. int Narticles = 100000; // size of the buffer to commit each time int commitBufferSize = 100; // N of articles to commit before trying reads int readStep = 100; String currentNamespace = "http://mynamespace#"; LOGGER.log(Level.INFO, "Generating the rdf..."); GenerateRdf rdfGenerator = new GenerateRdf(currentNamespace, "tmp.rdf"); rdfGenerator.generateAndSaveRdf(Narticles); LOGGER.log(Level.INFO, "Generated the rdf!"); ArrayList<SimulateReadAndWrite> simulateAll = new ArrayList<SimulateReadAndWrite>(); int Ndbs = 0; DBS[] chosenDbs = { DBS.NATIVE }; //DBS[] chosenDbs = DBS.values(); for (DBS dbs : chosenDbs) { SailRepository sr; switch (dbs) { case NATIVE: sr = createNativeStoreConnection(directory); break; case TITAN: sr = createTitanConnection(ip, keyspace); break; case NEO4J: sr = createNeo4jConnection(keyspace); break; case ORIENT: sr = createOrientConnection(keyspace); break; default: sr = null; break; } if (sr == null) { throw new Exception("Something wrong while connecting to " + dbs.toString()); } simulateAll.add(new SimulateReadAndWrite(sr, "test" + dbs.toString(), Narticles, readStep, commitBufferSize, dbs.toString(), keyspace, currentNamespace, rdfGenerator)); simulateAll.get(Ndbs).start(); Ndbs++; } int Nfinished = 0; int k; while (Nfinished != Ndbs) { Nfinished = 0; k = 0; for (DBS dbs : chosenDbs) { if (simulateAll.get(k).IsProcessCompleted()) { Nfinished++; } else { System.out.println(String.format("Process for db %s is at %.2f", dbs.toString(), simulateAll.get(k).GetProgress())); } k++; } Thread.sleep(10000); } } catch (Exception ex) { LOGGER.log(Level.SEVERE, null, ex); } }
From source file:com.datastax.dse.demos.solr.Wikipedia.java
public static void main(String[] args) { if (args.length == 0) usage();//from w ww. j a va 2 s.co m System.out.println("args: " + Arrays.asList(args)); // parse args for (int i = 0; i < args.length; i = i + 2) { if (args[i].startsWith("--")) { try { String arg = args[i].substring(2); String value = args[i + 1]; if (arg.equalsIgnoreCase("wikifile")) wikifile = value; if (arg.equalsIgnoreCase("limit")) limit = Integer.parseInt(value); if (arg.equalsIgnoreCase("host")) host = value; if (arg.equalsIgnoreCase("scheme")) scheme = value; if (arg.equalsIgnoreCase("user")) user = value; if (arg.equalsIgnoreCase("password")) password = value; } catch (Throwable t) { usage(); } } } url = String.format(urlTemplate, scheme, host); // Initialize Solr with our custom HTTP Client helpers - which handle // SSL & Kerberos. We must have dse.yaml on the classpath for this try { if (DseConfig.isSslEnabled()) { SolrHttpClientInitializer .initEncryption(new EncryptionOptions().withSSLContext(DseConfig.getSSLContext()) .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)); } if (DseConfig.isKerberosEnabled()) { // Obtain kerberos credentials from local ticket cache AuthenticationOptions options = new AuthenticationOptions(); if (DseConfig.isSslEnabled()) { options.withSSLContext(DseConfig.getSSLContext()) .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } SolrHttpClientInitializer.initAuthentication(options); } } catch (Exception e) { System.out.println("Fatal error when initializing Solr clients, exiting"); e.printStackTrace(); System.exit(1); } System.out.println("Start indexing wikipedia..."); long startTime = System.currentTimeMillis(); indexWikipedia(); long endTime = System.currentTimeMillis(); System.out.println("Finished"); System.exit(0); }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("u", null, true, "Solr URI"); options.addOption("q", null, true, "Query"); options.addOption("n", null, true, "Max # of results"); options.addOption("o", null, true, "An optional TREC-style output file"); options.addOption("w", null, false, "Do a warm-up query call, before each query"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter trecOutFile = null; try {// ww w. j a v a 2 s.c om CommandLine cmd = parser.parse(options, args); String queryFile = null, solrURI = null; if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } SolrServerWrapper solr = new SolrServerWrapper(solrURI); if (cmd.hasOption("q")) { queryFile = cmd.getOptionValue("q"); } else { Usage("Specify Query file"); } int numRet = 100; if (cmd.hasOption("n")) { numRet = Integer.parseInt(cmd.getOptionValue("n")); } if (cmd.hasOption("o")) { trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o")))); } List<String> fieldList = new ArrayList<String>(); fieldList.add(UtilConst.ID_FIELD); fieldList.add(UtilConst.SCORE_FIELD); double totalTime = 0; double retQty = 0; ArrayList<Double> queryTimes = new ArrayList<Double>(); boolean bDoWarmUp = cmd.hasOption("w"); if (bDoWarmUp) { System.out.println("Using a warmup step!"); } int queryQty = 0; for (String t : FileUtils.readLines(new File(queryFile))) { t = t.trim(); if (t.isEmpty()) continue; int ind = t.indexOf('|'); if (ind < 0) throw new Exception("Wrong format, line: '" + t + "'"); String qID = t.substring(0, ind); String q = t.substring(ind + 1); SolrDocumentList res = null; if (bDoWarmUp) { res = solr.runQuery(q, fieldList, numRet); } Long tm1 = System.currentTimeMillis(); res = solr.runQuery(q, fieldList, numRet); Long tm2 = System.currentTimeMillis(); retQty += res.getNumFound(); System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms"); double delta = (tm2 - tm1); totalTime += delta; queryTimes.add(delta); ++queryQty; if (trecOutFile != null) { ArrayList<SolrRes> resArr = new ArrayList<SolrRes>(); for (SolrDocument doc : res) { String id = (String) doc.getFieldValue(UtilConst.ID_FIELD); float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD); resArr.add(new SolrRes(id, "", score)); } SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]); Arrays.sort(results); SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length); } } double devTime = 0, meanTime = totalTime / queryQty; for (int i = 0; i < queryQty; ++i) { double d = queryTimes.get(i) - meanTime; devTime += d * d; } devTime = Math.sqrt(devTime / (queryQty - 1)); System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime)); System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty)); solr.close(); trecOutFile.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:com.act.lcms.db.io.report.IonAnalysisInterchangeModelOperations.java
public static void main(String[] args) throws IOException { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/* w w w.ja v a 2 s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(IonAnalysisInterchangeModelOperations.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(IonAnalysisInterchangeModelOperations.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption(OPTION_LOG_DISTRIBUTION)) { IonAnalysisInterchangeModel model = new IonAnalysisInterchangeModel(); model.loadResultsFromFile(new File(cl.getOptionValue(OPTION_INPUT_FILE))); Map<Pair<Double, Double>, Integer> rangeToCount = model .computeLogFrequencyDistributionOfMoleculeCountToMetric( IonAnalysisInterchangeModel.METRIC.valueOf(cl.getOptionValue(OPTION_LOG_DISTRIBUTION))); try (BufferedWriter predictionWriter = new BufferedWriter( new FileWriter(new File(OPTION_OUTPUT_FILE)))) { for (Map.Entry<Pair<Double, Double>, Integer> entry : rangeToCount.entrySet()) { String value = String.format("%f,%d", entry.getKey().getLeft(), entry.getValue()); predictionWriter.write(value); predictionWriter.newLine(); } } } }
From source file:io.crate.frameworks.mesos.Main.java
public static void main(String[] args) throws Exception { BasicConfigurator.configure();/*from w ww. j a v a 2 s .c o m*/ Configuration configuration = parseConfiguration(args); final double frameworkFailoverTimeout = 31536000d; // 60 * 60 * 24 * 365 = 1y final String webUri = UriBuilder.fromPath("/cluster").scheme("http").host(host()) .port(configuration.apiPort).build().toString(); Protos.FrameworkInfo.Builder frameworkBuilder = Protos.FrameworkInfo.newBuilder() .setName(configuration.frameworkName).setUser(configuration.user).setRole(configuration.role) .setWebuiUrl(webUri).setCheckpoint(true) // will be enabled by default in Mesos 0.22 .setFailoverTimeout(frameworkFailoverTimeout); PersistentStateStore stateStore = new PersistentStateStore( new ZooKeeperState(configuration.zookeeper, 20_000, TimeUnit.MILLISECONDS, String.format("/%s/%s", configuration.frameworkName, configuration.clusterName)), configuration.nodeCount); Optional<String> frameworkId = stateStore.state().frameworkId(); if (frameworkId.isPresent()) { frameworkBuilder.setId(Protos.FrameworkID.newBuilder().setValue(frameworkId.get()).build()); } final Scheduler scheduler = new CrateScheduler(stateStore, configuration); // create the driver MesosSchedulerDriver driver; String mesosMaster = configuration.mesosMaster(); Optional<Protos.Credential> credential = readCredentials(); if (credential.isPresent()) { frameworkBuilder.setPrincipal(credential.get().getPrincipal()); driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), mesosMaster, credential.get()); } else { frameworkBuilder.setPrincipal("crate-framework"); driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), mesosMaster); } CrateHttpService api = new CrateHttpService(stateStore, configuration); api.start(); int status = driver.run() == Protos.Status.DRIVER_STOPPED ? 0 : 1; // Ensure that the driver process terminates. api.stop(); driver.stop(); System.exit(status); }
From source file:apps.LuceneIndexer.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", null, true, "input file"); options.addOption("o", null, true, "output directory"); options.addOption("r", null, true, "optional output TREC-format QREL file"); options.addOption("bm25_b", null, true, "BM25 parameter: b"); options.addOption("bm25_k1", null, true, "BM25 parameter: k1"); options.addOption("bm25fixed", null, false, "use the fixed BM25 similarity"); Joiner commaJoin = Joiner.on(','); Joiner spaceJoin = Joiner.on(' '); options.addOption("source_type", null, true, "document source type: " + commaJoin.join(SourceFactory.getDocSourceList())); // If you increase this value, you may need to modify the following line in *.sh file // export MAVEN_OPTS="-Xms8192m -server" double ramBufferSizeMB = 1024 * 8; // 8 GB CommandLineParser parser = new org.apache.commons.cli.GnuParser(); IndexWriter indexWriter = null;//from w ww. java 2s . com BufferedWriter qrelWriter = null; int docNum = 0; try { CommandLine cmd = parser.parse(options, args); String inputFileName = null, outputDirName = null, qrelFileName = null; if (cmd.hasOption("i")) { inputFileName = cmd.getOptionValue("i"); } else { Usage("Specify 'input file'", options); } if (cmd.hasOption("o")) { outputDirName = cmd.getOptionValue("o"); } else { Usage("Specify 'index directory'", options); } if (cmd.hasOption("r")) { qrelFileName = cmd.getOptionValue("r"); } String sourceName = cmd.getOptionValue("source_type"); if (sourceName == null) Usage("Specify document source type", options); if (qrelFileName != null) qrelWriter = new BufferedWriter(new FileWriter(qrelFileName)); File outputDir = new File(outputDirName); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { System.out.println("couldn't create " + outputDir.getAbsolutePath()); System.exit(1); } } if (!outputDir.isDirectory()) { System.out.println(outputDir.getAbsolutePath() + " is not a directory!"); System.exit(1); } if (!outputDir.canWrite()) { System.out.println("Can't write to " + outputDir.getAbsolutePath()); System.exit(1); } boolean useFixedBM25 = cmd.hasOption("bm25fixed"); float bm25_k1 = UtilConst.BM25_K1_DEFAULT, bm25_b = UtilConst.BM25_B_DEFAULT; if (cmd.hasOption("bm25_k1")) { try { bm25_k1 = Float.parseFloat(cmd.getOptionValue("bm25_k1")); } catch (NumberFormatException e) { Usage("Wrong format for 'bm25_k1'", options); } } if (cmd.hasOption("bm25_b")) { try { bm25_b = Float.parseFloat(cmd.getOptionValue("bm25_b")); } catch (NumberFormatException e) { Usage("Wrong format for 'bm25_b'", options); } } EnglishAnalyzer analyzer = new EnglishAnalyzer(); FSDirectory indexDir = FSDirectory.open(Paths.get(outputDirName)); IndexWriterConfig indexConf = new IndexWriterConfig(analyzer); /* OpenMode.CREATE creates a new index or overwrites an existing one. https://lucene.apache.org/core/6_0_0/core/org/apache/lucene/index/IndexWriterConfig.OpenMode.html#CREATE */ indexConf.setOpenMode(OpenMode.CREATE); indexConf.setRAMBufferSizeMB(ramBufferSizeMB); System.out.println(String.format("BM25 parameters k1=%f b=%f ", bm25_k1, bm25_b)); if (useFixedBM25) { System.out.println(String.format("Using fixed BM25Simlarity, k1=%f b=%f", bm25_k1, bm25_b)); indexConf.setSimilarity(new BM25SimilarityFix(bm25_k1, bm25_b)); } else { System.out.println(String.format("Using Lucene BM25Similarity, k1=%f b=%f", bm25_k1, bm25_b)); indexConf.setSimilarity(new BM25Similarity(bm25_k1, bm25_b)); } indexWriter = new IndexWriter(indexDir, indexConf); DocumentSource inpDocSource = SourceFactory.createDocumentSource(sourceName, inputFileName); DocumentEntry inpDoc = null; TextCleaner textCleaner = new TextCleaner(null); while ((inpDoc = inpDocSource.next()) != null) { ++docNum; Document luceneDoc = new Document(); ArrayList<String> cleanedToks = textCleaner.cleanUp(inpDoc.mDocText); String cleanText = spaceJoin.join(cleanedToks); // System.out.println(inpDoc.mDocId); // System.out.println(cleanText); // System.out.println("=============================="); luceneDoc.add(new StringField(UtilConst.FIELD_ID, inpDoc.mDocId, Field.Store.YES)); luceneDoc.add(new TextField(UtilConst.FIELD_TEXT, cleanText, Field.Store.YES)); indexWriter.addDocument(luceneDoc); if (inpDoc.mIsRel != null && qrelWriter != null) { saveQrelOneEntry(qrelWriter, inpDoc.mQueryId, inpDoc.mDocId, inpDoc.mIsRel ? MAX_GRADE : 0); } if (docNum % 1000 == 0) System.out.println(String.format("Indexed %d documents", docNum)); } } catch (ParseException e) { e.printStackTrace(); Usage("Cannot parse arguments" + e, options); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } finally { System.out.println(String.format("Indexed %d documents", docNum)); try { if (null != indexWriter) indexWriter.close(); if (null != qrelWriter) qrelWriter.close(); } catch (IOException e) { System.err.println("IO exception: " + e); e.printStackTrace(); } } }
From source file:com.oz.digital.sign.window.MainView.java
/** * @param args the command line arguments *///from www .j a va 2s .c o m public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("GTK+".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { LOG.log(Level.SEVERE, null, ex); } //</editor-fold> MainView mainView = new MainView(); mainView.setVisible(true); while (true) { final String entry = mainView.getTxtfEntry().getText(); if (StringUtils.isNotBlank(entry)) { LOG.log(Level.INFO, "== Agregando la entrada : {0}", entry); String entryFormatted = String.format("%s -> %s\n", DateFormatUtils.format(new Date(), "dd/MM/yyyy hh:mm:ss"), entry); mainView.getTxtAreaEntryHistory().append(entryFormatted); } try { Thread.sleep(5000); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, ex.getMessage()); } } }
From source file:com.github.brandtg.switchboard.MysqlReplicator.java
/** Main. */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("u", "user", true, "MySQL user"); options.addOption("p", "password", true, "MySQL password"); options.addOption("h", "host", true, "MySQL host"); options.addOption("P", "port", true, "MySQL port"); options.addOption("s", "sinkPort", true, "Local sink port"); options.addOption("l", "lastIndex", true, "Last transaction ID"); options.addOption("h", "help", false, "Prints help message"); CommandLine commandLine = new GnuParser().parse(options, args); if (commandLine.getArgs().length < 2 || commandLine.hasOption("help")) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("usage: [opts] switchboardHost:port db1 [db2 ...]", options); System.exit(1);// www .jav a 2 s. c om } // Switchboard host String[] hostPort = commandLine.getArgs()[0].split(":"); InetSocketAddress source = new InetSocketAddress(hostPort[0], Integer.valueOf(hostPort[1])); InetSocketAddress sink = new InetSocketAddress( Integer.valueOf(commandLine.getOptionValue("sinkPort", "9090"))); // Databases to replicate String[] databases = Arrays.copyOfRange(commandLine.getArgs(), 1, commandLine.getArgs().length); // JDBC params for local copy String user = commandLine.getOptionValue("user", "root"); String password = commandLine.getOptionValue("password", ""); String jdbcString = String.format("jdbc:mysql://%s:%d", commandLine.getOptionValue("host", "localhost"), Integer.valueOf(commandLine.getOptionValue("port", "3306"))); Long lastIndex = Long.valueOf(commandLine.getOptionValue("lastIndex", "-1")); // Create replicators final List<MysqlReplicator> replicators = new ArrayList<>(); for (String database : databases) { MysqlReplicator replicator = new MysqlReplicator(database, source, sink, jdbcString, user, password, lastIndex); replicators.add(replicator); } // Shutdown hook Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (MysqlReplicator replicator : replicators) { try { replicator.shutdown(); } catch (Exception e) { LOG.error("Could not shut down {}", replicator, e); } } } }); for (MysqlReplicator replicator : replicators) { replicator.start(); LOG.info("Started {}", replicator); } }