List of usage examples for java.lang System getProperty
public static String getProperty(String key)
From source file:com.joliciel.talismane.terminology.TalismaneTermExtractorMain.java
public static void main(String[] args) throws Exception { String termFilePath = null;/*w ww .j a v a 2s . c o m*/ String outFilePath = null; Command command = Command.extract; int depth = -1; String databasePropertiesPath = null; String projectCode = null; String terminologyPropertiesPath = null; Map<String, String> argMap = StringUtils.convertArgs(args); String logConfigPath = argMap.get("logConfigFile"); if (logConfigPath != null) { argMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } Map<String, String> innerArgs = new HashMap<String, String>(); for (Entry<String, String> argEntry : argMap.entrySet()) { String argName = argEntry.getKey(); String argValue = argEntry.getValue(); if (argName.equals("command")) command = Command.valueOf(argValue); else if (argName.equals("termFile")) termFilePath = argValue; else if (argName.equals("outFile")) outFilePath = argValue; else if (argName.equals("depth")) depth = Integer.parseInt(argValue); else if (argName.equals("databaseProperties")) databasePropertiesPath = argValue; else if (argName.equals("terminologyProperties")) terminologyPropertiesPath = argValue; else if (argName.equals("projectCode")) projectCode = argValue; else innerArgs.put(argName, argValue); } if (termFilePath == null && databasePropertiesPath == null) throw new TalismaneException("Required argument: termFile or databasePropertiesPath"); if (termFilePath != null) { String currentDirPath = System.getProperty("user.dir"); File termFileDir = new File(currentDirPath); if (termFilePath.lastIndexOf("/") >= 0) { String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/")); termFileDir = new File(termFileDirPath); termFileDir.mkdirs(); } } long startTime = new Date().getTime(); try { if (command.equals(Command.analyse)) { innerArgs.put("command", "analyse"); } else { innerArgs.put("command", "process"); } String sessionId = ""; TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId); TalismaneService talismaneService = locator.getTalismaneService(); TalismaneConfig config = talismaneService.getTalismaneConfig(innerArgs, sessionId); TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(locator); TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService(); TerminologyBase terminologyBase = null; if (projectCode == null) throw new TalismaneException("Required argument: projectCode"); File file = new File(databasePropertiesPath); FileInputStream fis = new FileInputStream(file); Properties dataSourceProperties = new Properties(); dataSourceProperties.load(fis); terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties); TalismaneSession talismaneSession = talismaneService.getTalismaneSession(); if (command.equals(Command.analyse) || command.equals(Command.extract)) { Locale locale = talismaneSession.getLocale(); Map<TerminologyProperty, String> terminologyProperties = new HashMap<TerminologyProperty, String>(); if (terminologyPropertiesPath != null) { Map<String, String> terminologyPropertiesStr = StringUtils.getArgMap(terminologyPropertiesPath); for (String key : terminologyPropertiesStr.keySet()) { try { TerminologyProperty property = TerminologyProperty.valueOf(key); terminologyProperties.put(property, terminologyPropertiesStr.get(key)); } catch (IllegalArgumentException e) { throw new TalismaneException("Unknown terminology property: " + key); } } } else { terminologyProperties = getDefaultTerminologyProperties(locale); } if (depth <= 0 && !terminologyProperties.containsKey(TerminologyProperty.maxDepth)) throw new TalismaneException("Required argument: depth"); InputStream regexInputStream = getInputStreamFromResource( "parser_conll_with_location_input_regex.txt"); Scanner regexScanner = new Scanner(regexInputStream, "UTF-8"); String inputRegex = regexScanner.nextLine(); regexScanner.close(); config.setInputRegex(inputRegex); Charset outputCharset = config.getOutputCharset(); TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase, terminologyProperties); if (depth > 0) termExtractor.setMaxDepth(depth); termExtractor.setOutFilePath(termFilePath); if (outFilePath != null) { if (outFilePath.lastIndexOf("/") >= 0) { String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/")); File outFileDir = new File(outFileDirPath); outFileDir.mkdirs(); } File outFile = new File(outFilePath); outFile.delete(); outFile.createNewFile(); Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset)); TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer); termExtractor.addTermObserver(termAnalysisWriter); } Talismane talismane = config.getTalismane(); talismane.setParseConfigurationProcessor(termExtractor); talismane.process(); } else if (command.equals(Command.list)) { List<Term> terms = terminologyBase.findTerms(2, null, 0, null, null); for (Term term : terms) { LOG.debug("Term: " + term.getText()); LOG.debug("Frequency: " + term.getFrequency()); LOG.debug("Heads: " + term.getHeads()); LOG.debug("Expansions: " + term.getExpansions()); LOG.debug("Contexts: " + term.getContexts()); } } } finally { long endTime = new Date().getTime(); long totalTime = endTime - startTime; LOG.info("Total time: " + totalTime); } }
From source file:jh.tools.office.ConvertOutPDF.java
public static void main(String[] args) throws Exception { try {/* w ww.ja va 2 s .co m*/ getInputFilePath(args); } catch (IllegalArgumentException e) { } // Font regex (optional) // Set regex if you want to restrict to some defined subset of fonts // Here we have to do this before calling createContent, // since that discovers fonts String regex = null; // Windows: // String // regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*"; //regex=".*(calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*"; // Mac // String // regex=".*(Courier New|Arial|Times New Roman|Comic Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS Serif).*"; PhysicalFonts.setRegex(regex); // Document loading (required) WordprocessingMLPackage wordMLPackage; // Load .docx or Flat OPC .xml System.out.println("Loading file from " + inputfilepath); wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath)); // Refresh the values of DOCPROPERTY fields FieldUpdater updater = new FieldUpdater(wordMLPackage); //updater.update(true); String outputfilepath; if (inputfilepath == null) { outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf"; } else { outputfilepath = inputfilepath + ".pdf"; } // All methods write to an output stream OutputStream os = new java.io.FileOutputStream(outputfilepath); if (!Docx4J.pdfViaFO()) { // Since 3.3.0, Plutext's PDF Converter is used by default System.out.println("Using Plutext's PDF Converter; add docx4j-export-fo if you don't want that"); try { Docx4J.toPDF(wordMLPackage, os); } catch (Docx4JException e) { e.printStackTrace(); // What did we write? IOUtils.closeQuietly(os); System.out.println(FileUtils.readFileToString(new File(outputfilepath))); if (e.getCause() != null && e.getCause() instanceof ConversionException) { ConversionException ce = (ConversionException) e.getCause(); ce.printStackTrace(); } } System.out.println("Saved: " + outputfilepath); return; } System.out.println("Attempting to use XSL FO"); /** * Demo of PDF output. * * PDF output is via XSL FO. * First XSL FO is created, then FOP * is used to convert that to PDF. * * Don't worry if you get a class not * found warning relating to batik. It * doesn't matter. * * If you don't have logging configured, * your PDF will say "TO HIDE THESE MESSAGES, * TURN OFF debug level logging for * org.docx4j.convert.out.pdf.viaXSLFO". The thinking is * that you need to be able to be warned if there * are things in your docx which the PDF output * doesn't support... * * docx4j used to also support creating * PDF via iText and via HTML. As of docx4j 2.5.0, * only viaXSLFO is supported. The viaIText and * viaHTML source code can be found in src/docx4j-extras directory * */ /* * NOT WORKING? * * If you are getting: * * "fo:layout-master-set" must be declared before "fo:page-sequence" * * please check: * * 1. the jaxb-xslfo jar is on your classpath * * 2. that there is no stack trace earlier in the logs * * 3. your JVM has adequate memory, eg * * -Xmx1G -XX:MaxPermSize=128m * */ // Set up font mapper (optional) Mapper fontMapper = new IdentityPlusMapper(); wordMLPackage.setFontMapper(fontMapper); fontMapper.put("", PhysicalFonts.get("LiSu")); fontMapper.put("", PhysicalFonts.get("SimSun")); fontMapper.put("", PhysicalFonts.get("Microsoft Yahei")); fontMapper.put("", PhysicalFonts.get("SimHei")); fontMapper.put("", PhysicalFonts.get("KaiTi")); fontMapper.put("", PhysicalFonts.get("NSimSun")); fontMapper.put("?", PhysicalFonts.get("STXingkai")); fontMapper.put("?", PhysicalFonts.get("STFangsong")); fontMapper.put("", PhysicalFonts.get("simsun-extB")); fontMapper.put("", PhysicalFonts.get("FangSong")); fontMapper.put("_GB2312", PhysicalFonts.get("FangSong_GB2312")); fontMapper.put("", PhysicalFonts.get("YouYuan")); fontMapper.put("?", PhysicalFonts.get("STSong")); fontMapper.put("?", PhysicalFonts.get("STZhongsong")); // .. example of mapping font Times New Roman which doesn't have certain Arabic glyphs // eg Glyph "" (0x64a, afii57450) not available in font "TimesNewRomanPS-ItalicMT". // eg Glyph "" (0x62c, afii57420) not available in font "TimesNewRomanPS-ItalicMT". // to a font which does PhysicalFont font = PhysicalFonts.get("Arial Unicode MS"); // make sure this is in your regex (if any)!!! // if (font!=null) { // fontMapper.put("Times New Roman", font); // fontMapper.put("Arial", font); // } // fontMapper.put("Libian SC Regular", PhysicalFonts.get("SimSun")); // FO exporter setup (required) // .. the FOSettings object FOSettings foSettings = Docx4J.createFOSettings(); if (saveFO) { foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo")); } foSettings.setWmlPackage(wordMLPackage); // Document format: // The default implementation of the FORenderer that uses Apache Fop will output // a PDF document if nothing is passed via // foSettings.setApacheFopMime(apacheFopMime) // apacheFopMime can be any of the output formats defined in org.apache.fop.apps.MimeConstants eg org.apache.fop.apps.MimeConstants.MIME_FOP_IF or // FOSettings.INTERNAL_FO_MIME if you want the fo document as the result. //foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME); // Specify whether PDF export uses XSLT or not to create the FO // (XSLT takes longer, but is more complete). // Don't care what type of exporter you use Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL); // Prefer the exporter, that uses a xsl transformation // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL); // Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor) // .. faster, but not yet at feature parity // Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL); System.out.println("Saved: " + outputfilepath); // Clean up, so any ObfuscatedFontPart temp files can be deleted if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) { wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles(); } // This would also do it, via finalize() methods updater = null; foSettings = null; wordMLPackage = null; }
From source file:com.adobe.aem.demomachine.gui.AemDemo.java
public static void main(String[] args) { String demoMachineRootFolder = null; // Command line options for this tool Options options = new Options(); options.addOption("f", true, "Path to Demo Machine root folder"); CommandLineParser parser = new BasicParser(); try {/*from ww w . j av a2 s . c o m*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { demoMachineRootFolder = cmd.getOptionValue("f"); } } catch (ParseException ex) { logger.error(ex.getMessage()); } // Let's grab the version number for the core Maven file String mavenFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder : System.getProperty("user.dir")) + File.separator + "java" + File.separator + "core" + File.separator + "pom.xml"; File mavenFile = new File(mavenFilePath); if (mavenFile.exists() && !mavenFile.isDirectory()) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document; document = builder.parse(mavenFile); NodeList list = document.getElementsByTagName("version"); if (list != null && list.getLength() > 0) { aemDemoMachineVersion = list.item(0).getFirstChild().getNodeValue(); } } catch (Exception e) { logger.error("Can't parse Maven pom.xml file"); } } // Let's check if we have a valid build.xml file to work with... String buildFilePath = (demoMachineRootFolder != null ? demoMachineRootFolder : System.getProperty("user.dir")) + File.separator + "build.xml"; logger.debug("Trying to load build file from " + buildFilePath); buildFile = new File(buildFilePath); if (buildFile.exists() && !buildFile.isDirectory()) { // Launching the main window EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.getLookAndFeelDefaults().put("defaultFont", new Font("Arial", Font.BOLD, 14)); AemDemo window = new AemDemo(); window.frameMain.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } else { logger.error("No valid build.xml file to work with"); System.exit(-1); } }
From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java
public static void main(String[] args) throws Exception { Parser parser = new PosixParser(); Options options = new Options(); options.addOption("r", "repo", true, "Repository type to search: local|central"); options.addOption("c", "client-concurrency", true, "Max threads to allow each client tester to run tests, defaults to 10"); options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5"); options.addOption("m", "max-time", true, "Max time (in minutes) to allow tests to complete, defaults to 10"); options.addOption("v", "version", false, "Print version and exit"); options.addOption("h", "help", false, "This help text"); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { System.out.println(options); System.exit(0);//from www. j a va 2 s. co m } if (commandLine.hasOption("v")) { System.out.println("How the hell should I know?"); System.exit(0); } // 1. Find all testers in given repos List<RepoSearcher> repoSearchers = new ArrayList<>(); for (String repo : commandLine.getOptionValues("r")) { if ("local".equals(repo.toLowerCase())) { repoSearchers.add(new LocalRepoSearcher()); } else if ("central".equals(repo.toLowerCase())) { repoSearchers.add(new CentralRepoSearcher()); } else { System.err.println("Unrecognized repo: " + repo); System.err.println(options); System.exit(1); } } int clientConcurrency = 10; if (commandLine.hasOption("c")) { try { clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c")); } catch (NumberFormatException nfe) { System.err.println( "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'"); System.exit(1); } } int testConcurrency = 5; if (commandLine.hasOption("t")) { try { testConcurrency = Integer.parseInt(commandLine.getOptionValue("t")); } catch (NumberFormatException nfe) { System.err.println( "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'"); System.exit(1); } } int maxMinutes = 10; if (commandLine.hasOption("m")) { try { maxMinutes = Integer.parseInt(commandLine.getOptionValue("m")); } catch (NumberFormatException nfe) { System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'"); System.exit(1); } } Properties clientProps = new Properties(); clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency)); File baseRunDir = new File(System.getProperty("user.dir") + "/run"); baseRunDir.mkdirs(); File tmpDir = new File(baseRunDir, "jars"); tmpDir.mkdirs(); List<ServerRunner> serverRunners = new ArrayList<>(); List<ClientRunner> clientRunners = new ArrayList<>(); for (RepoSearcher searcher : repoSearchers) { List<File> jars = searcher.findAndCache(tmpDir); for (File f : jars) { ServerRunner serverRunner = new ServerRunner(f, baseRunDir); System.out.println("Found tester: " + serverRunner.getVersion()); serverRunners.add(serverRunner); clientRunners.add(new ClientRunner(f, baseRunDir, clientProps)); } } // 2. Start servers and collect ports System.out.println(); System.out.println("Starting " + serverRunners.size() + " servers..."); for (ServerRunner server : serverRunners) { server.startServer(); } System.out.println(); List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size()); for (ServerRunner server : serverRunners) { for (ClientRunner client : clientRunners) { tests.add(new TestCombo(server, client)); } } System.out.println("Enqueued " + tests.size() + " test combos to run..."); long startTime = System.currentTimeMillis(); // 3. Run every client against every server, collecting results BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size()); ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000, TimeUnit.MILLISECONDS, workQueue); service.prestartAllCoreThreads(); workQueue.addAll(tests); while (!workQueue.isEmpty()) { Thread.sleep(1000); } service.shutdown(); service.awaitTermination(maxMinutes, TimeUnit.MINUTES); long endTime = System.currentTimeMillis(); long totalTimeSecs = Math.round((endTime - startTime) / 1000.0); for (ServerRunner server : serverRunners) { server.shutdownServer(); } System.out.println(); System.out.println("======="); System.out.println("Results"); System.out.println("-------"); // print a summary int totalTests = 0; int totalSuccess = 0; for (TestCombo combo : tests) { String clientVer = combo.getClientVersion(); String serverVer = combo.getServerVersion(); String results = combo.getClientResults(); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode node = mapper.reader().readTree(results); JsonNode resultsArray = node.get("results"); int numTests = resultsArray.size(); int numSuccess = 0; for (int i = 0; i < numTests; i++) { if ("success".equals(resultsArray.get(i).get("result").asText())) { numSuccess++; } } totalSuccess += numSuccess; totalTests += numTests; System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds"); } System.out.println("-------"); System.out.println( "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds"); FileWriter out = new FileWriter("results.json"); PrintWriter pw = new PrintWriter(out); // 4. Output full results pw.println("{\n \"results\": ["); for (TestCombo combo : tests) { combo.emitResults(pw, " "); } pw.println(" ],"); pw.println(" \"servers\": ["); for (ServerRunner server : serverRunners) { server.emitInfo(pw, " "); } pw.println(" ],"); pw.close(); }
From source file:it.anyplace.sync.client.Main.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("C", "set-config", true, "set config file for s-client"); options.addOption("c", "config", false, "dump config"); options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers"); options.addOption("q", "query", true, "query directory server for device id"); options.addOption("d", "discovery", true, "discovery local network for device id"); options.addOption("p", "pull", true, "pull file from network"); options.addOption("P", "push", true, "push file to network"); options.addOption("o", "output", true, "set output file/directory"); options.addOption("i", "input", true, "set input file/directory"); options.addOption("lp", "list-peers", false, "list peer addresses"); options.addOption("a", "address", true, "use this peer addresses"); options.addOption("L", "list-remote", false, "list folder (root) content from network"); options.addOption("I", "list-info", false, "dump folder info from network"); options.addOption("li", "list-info", false, "list folder info from local db"); // options.addOption("l", "list-local", false, "list folder content from local (saved) index"); options.addOption("s", "search", true, "search local index for <term>"); options.addOption("D", "delete", true, "push delete to network"); options.addOption("M", "mkdir", true, "push directory create to network"); options.addOption("h", "help", false, "print help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("s-client", options); return;// www. j a v a 2 s. c om } File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C")) : new File(System.getProperty("user.home"), ".s-client.properties"); logger.info("using config file = {}", configFile); ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile); FileUtils.cleanDirectory(configuration.getTemp()); KeystoreHandler.newLoader().loadAndStore(configuration); if (cmd.hasOption("c")) { logger.info("configuration =\n{}", configuration.newWriter().dumpToString()); } else { logger.trace("configuration =\n{}", configuration.newWriter().dumpToString()); } logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace()); if (cmd.hasOption("sp")) { List<String> peers = Lists.newArrayList(Lists.transform( Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() { @Override public String apply(String input) { return input.trim(); } })); logger.info("set peers = {}", peers); configuration.edit().setPeers(Collections.<DeviceInfo>emptyList()); for (String peer : peers) { KeystoreHandler.validateDeviceId(peer); configuration.edit().addPeers(new DeviceInfo(peer, null)); } configuration.edit().persistNow(); } if (cmd.hasOption("q")) { String deviceId = cmd.getOptionValue("q"); logger.info("query device id = {}", deviceId); List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId); logger.info("server response = {}", deviceAddresses); } if (cmd.hasOption("d")) { String deviceId = cmd.getOptionValue("d"); logger.info("discovery device id = {}", deviceId); List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId); logger.info("local response = {}", deviceAddresses); } if (cmd.hasOption("p")) { String path = cmd.getOptionValue("p"); logger.info("file path = {}", path); String folder = path.split(":")[0]; path = path.split(":")[1]; try (SyncthingClient client = new SyncthingClient(configuration); BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) { InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete() .getInputStream(); String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName(); File file; if (cmd.hasOption("o")) { File param = new File(cmd.getOptionValue("o")); file = param.isDirectory() ? new File(param, fileName) : param; } else { file = new File(fileName); } FileUtils.copyInputStreamToFile(inputStream, file); logger.info("saved file to = {}", file.getAbsolutePath()); } } if (cmd.hasOption("P")) { String path = cmd.getOptionValue("P"); File file = new File(cmd.getOptionValue("i")); checkArgument(!path.startsWith("/")); //TODO check path syntax logger.info("file path = {}", path); String folder = path.split(":")[0]; path = path.split(":")[1]; try (SyncthingClient client = new SyncthingClient(configuration); BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file), folder, path)) { while (!fileUploadObserver.isCompleted()) { fileUploadObserver.waitForProgressUpdate(); logger.debug("upload progress {}", fileUploadObserver.getProgressMessage()); } logger.info("uploaded file to network"); } } if (cmd.hasOption("D")) { String path = cmd.getOptionValue("D"); String folder = path.split(":")[0]; path = path.split(":")[1]; logger.info("delete path = {}", path); try (SyncthingClient client = new SyncthingClient(configuration); IndexEditObserver observer = client.pushDelete(folder, path)) { observer.waitForComplete(); logger.info("deleted path"); } } if (cmd.hasOption("M")) { String path = cmd.getOptionValue("M"); String folder = path.split(":")[0]; path = path.split(":")[1]; logger.info("dir path = {}", path); try (SyncthingClient client = new SyncthingClient(configuration); IndexEditObserver observer = client.pushDir(folder, path)) { observer.waitForComplete(); logger.info("uploaded dir to network"); } } if (cmd.hasOption("L")) { try (SyncthingClient client = new SyncthingClient(configuration)) { client.waitForRemoteIndexAquired(); for (String folder : client.getIndexHandler().getFolderList()) { try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder() .setFolder(folder).build()) { logger.info("list folder = {}", indexBrowser.getFolder()); for (FileInfo fileInfo : indexBrowser.listFiles()) { logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(), fileInfo.describeSize()); } } } } } if (cmd.hasOption("I")) { try (SyncthingClient client = new SyncthingClient(configuration)) { if (cmd.hasOption("a")) { String deviceId = cmd.getOptionValue("a").substring(0, 63), address = cmd.getOptionValue("a").substring(64); try (BlockExchangeConnectionHandler connection = client.getConnection( DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) { client.getIndexHandler().waitForRemoteIndexAquired(connection); } } else { client.waitForRemoteIndexAquired(); } String folderInfo = ""; for (String folder : client.getIndexHandler().getFolderList()) { folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder); folderInfo += "\n\t\tfolder stats : " + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n"; } logger.info("folders:\n{}\n", folderInfo); } } if (cmd.hasOption("li")) { try (SyncthingClient client = new SyncthingClient(configuration)) { String folderInfo = ""; for (String folder : client.getIndexHandler().getFolderList()) { folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder); folderInfo += "\n\t\tfolder stats : " + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n"; } logger.info("folders:\n{}\n", folderInfo); } } if (cmd.hasOption("lp")) { try (SyncthingClient client = new SyncthingClient(configuration); DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler() .newDeviceAddressSupplier()) { String deviceAddressesStr = ""; for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) { deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : " + deviceAddress.getAddress(); } logger.info("device addresses:\n{}\n", deviceAddressesStr); } } if (cmd.hasOption("s")) { String term = cmd.getOptionValue("s"); try (SyncthingClient client = new SyncthingClient(configuration); IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) { client.waitForRemoteIndexAquired(); logger.info("search term = '{}'", term); IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term); if (event.hasGoodResults()) { logger.info("search results for term = '{}' :", term); for (FileInfo fileInfo : event.getResultList()) { logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(), fileInfo.describeSize()); } } else if (event.hasTooManyResults()) { logger.info("too many results found for term = '{}'", term); } else { logger.info("no result found for term = '{}'", term); } } } // if (cmd.hasOption("l")) { // String indexDump = new IndexHandler(configuration).dumpIndex(); // logger.info("index dump = \n\n{}\n", indexDump); // } IOUtils.closeQuietly(configuration); }
From source file:com.glaf.core.util.AnnotationUtils.java
public static void main(String[] args) throws Exception { System.out.println(System.getProperty("java.class.path")); long start = System.currentTimeMillis(); Collection<String> entities = AnnotationUtils.findMapper("com.glaf"); long time = System.currentTimeMillis() - start; for (String str : entities) { System.out.println(str);//from w ww . j a va 2 s . c om } System.out.println("time:" + time); URL[] urls = ClasspathUrlFinder.findResourceBases("com/glaf/package.properties", Thread.currentThread().getContextClassLoader()); for (URL url2 : urls) { logger.debug("->scan url:" + url2.toURI().toString()); } }
From source file:com.mgmtp.perfload.core.daemon.LtDaemon.java
public static void main(final String... args) { JCommander jCmd = null;/*from ww w . j a v a2 s . c o m*/ try { LtDaemonArgs cliArgs = new LtDaemonArgs(); jCmd = new JCommander(cliArgs); jCmd.parse(args); log().info("Starting perfLoad Daemon..."); log().info(cliArgs.toString()); if (cliArgs.shutdown) { shutdownDaemon(cliArgs.port); System.exit(0); } // Client is expected next to the daemon File clientDir = new File(new File(System.getProperty("user.dir")).getParentFile(), "client"); ExecutorService execService = Executors.newCachedThreadPool(); StreamGobbler gobbler = new StreamGobbler(execService); Server server = new DefaultServer(cliArgs.port); LtDaemon daemon = new LtDaemon(clientDir, new ForkedProcessClientRunner(execService, gobbler), server); daemon.execute(); execService.shutdown(); execService.awaitTermination(10L, TimeUnit.SECONDS); System.exit(0); } catch (ParameterException ex) { jCmd.usage(); System.exit(1); } catch (Exception ex) { log().error(ex.getMessage(), ex); System.exit(-1); } }
From source file:ru.phsystems.irisx.voice.httpPOST.java
/** * Test function main.../*ww w .j av a2 s . co m*/ */ public static void main(String[] args) { // Test the post Request ... httpPOST flacPost = new httpPOST(); flacPost.postFile(System.getProperty("user.dir") + "/recording.flac"); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.CollectionDiffer.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i1", null, true, "Input file 1"); options.addOption("i2", null, true, "Input file 2"); options.addOption("o", null, true, "Output file"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {// w ww . j a va 2 s . c o m CommandLine cmd = parser.parse(options, args); InputStream input1 = null, input2 = null; if (cmd.hasOption("i1")) { input1 = CompressUtils.createInputStream(cmd.getOptionValue("i1")); } else { Usage("Specify 'Input file 1'"); } if (cmd.hasOption("i2")) { input2 = CompressUtils.createInputStream(cmd.getOptionValue("i2")); } else { Usage("Specify 'Input file 2'"); } HashSet<String> hSubj = new HashSet<String>(); BufferedWriter out = null; if (cmd.hasOption("o")) { String outFile = cmd.getOptionValue("o"); out = new BufferedWriter(new OutputStreamWriter(CompressUtils.createOutputStream(outFile))); } else { Usage("Specify 'Output file'"); } XmlIterator inpIter2 = new XmlIterator(input2, YahooAnswersReader.DOCUMENT_TAG); int docNum = 1; for (String oneRec = inpIter2.readNext(); !oneRec.isEmpty(); oneRec = inpIter2.readNext(), ++docNum) { if (docNum % 10000 == 0) { System.out.println(String.format( "Loaded and memorized questions for %d documents from the second input file", docNum)); } ParsedQuestion q = YahooAnswersParser.parse(oneRec, false); hSubj.add(q.mQuestion); } XmlIterator inpIter1 = new XmlIterator(input1, YahooAnswersReader.DOCUMENT_TAG); System.out.println("============================================="); System.out.println("Memoization is done... now let's diff!!!"); System.out.println("============================================="); docNum = 1; int skipOverlapQty = 0, skipErrorQty = 0; for (String oneRec = inpIter1.readNext(); !oneRec.isEmpty(); ++docNum, oneRec = inpIter1.readNext()) { if (docNum % 10000 == 0) { System.out.println(String.format("Processed %d documents from the first input file", docNum)); } oneRec = oneRec.trim() + System.getProperty("line.separator"); ParsedQuestion q = null; try { q = YahooAnswersParser.parse(oneRec, false); } catch (Exception e) { // If <bestanswer>...</bestanswer> is missing we may end up here... // This is a bit funny, because this element is supposed to be mandatory, // but it's not. System.err.println("Skipping due to parsing error, exception: " + e); skipErrorQty++; continue; } if (hSubj.contains(q.mQuestion.trim())) { //System.out.println(String.format("Skipping uri='%s', question='%s'", q.mQuestUri, q.mQuestion)); skipOverlapQty++; continue; } out.write(oneRec); } System.out.println( String.format("Processed %d documents, skipped because of overlap/errors %d/%d documents", docNum - 1, skipOverlapQty, skipErrorQty)); out.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:FDLRequestor.java
public static void main(String[] args) throws Exception { String hostId = ""; String partnerId = ""; String userId = ""; CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "host", true, "EBICS Host ID"); options.addOption("p", "partner", true, "Registred Partner ID for you user"); options.addOption("u", "user", true, "User ID to initiate"); // Parse the program arguments CommandLine commandLine = parser.parse(options, args); if (!commandLine.hasOption('h')) { System.out.println("Host-ID is mandatory"); System.exit(0);/*from ww w .j a va 2s . c o m*/ } else { hostId = commandLine.getOptionValue('h'); System.out.println("host: " + hostId); } if (!commandLine.hasOption('p')) { System.out.println("Partner-ID is mandatory"); System.exit(0); } else { partnerId = commandLine.getOptionValue('p'); System.out.println("partnerId: " + partnerId); } if (!commandLine.hasOption('u')) { System.out.println("User-ID is mandatory"); System.exit(0); } else { userId = commandLine.getOptionValue('u'); System.out.println("userId: " + userId); } FDLRequestor fdlRequestor; PasswordCallback pwdHandler; Product product; String filePath; fdlRequestor = new FDLRequestor(); product = new Product("kopiLeft Dev 1.0", Locale.FRANCE, null); pwdHandler = new UserPasswordHandler(userId, "2012"); // Load alredy created user fdlRequestor.loadUser(hostId, partnerId, userId, pwdHandler); filePath = System.getProperty("user.home") + File.separator + "download.txt"; // Send FDL Requets fdlRequestor.fetchFile(filePath, userId, product, OrderType.FDL, true, null, null); }