List of usage examples for java.lang String indexOf
public int indexOf(String str)
From source file:com.icebreak.p2p.trade.impl.TradeServiceImpl.java
public static void main(String[] args) { String guaranteeLicenseNoNew = ""; String guaranteeLicenseNo = "??TRB?[2013]001?"; String strDate = "20131112"; int count = 1; if (guaranteeLicenseNo.indexOf("?") > 0) { String prefix = guaranteeLicenseNo.substring(0, guaranteeLicenseNo.indexOf("?")); guaranteeLicenseNoNew = prefix + "[" + strDate.substring(0, 4) + "]" + strDate.substring(4, strDate.length()) + StringUtils.leftPad(String.valueOf(++count), 3, "0") + "?"; } else {//from www . ja v a2 s . c o m String prefix = guaranteeLicenseNo.substring(0, guaranteeLicenseNo.indexOf("TRB") + 3); guaranteeLicenseNoNew = prefix + "[" + strDate.substring(0, 4) + "]" + strDate.substring(4, strDate.length()) + StringUtils.leftPad(String.valueOf(++count), 3, "0") + "?"; } System.out.println(guaranteeLicenseNoNew); }
From source file:com.termmed.statistics.runner.Runner.java
/** * The main method./*from w w w . ja v a2 s. co m*/ * * @param args the arguments */ public static void main(String[] args) { logger = new ProcessLogger(); if (args.length == 0) { logger.logInfo("Error happened getting params. Params file doesn't exist"); System.exit(0); // }else{ // args=new String[]{"config/complete_nl-edition11320160930.xml"}; } File infoFolder = new File(I_Constants.PROCESS_INFO_FOLDER); if (!infoFolder.exists()) { infoFolder.mkdirs(); } OutputInfoFactory.get().setExecutionId(UUID.randomUUID().toString()); String msg; int posIni; long start = logger.startTime(); File file = new File(args[0]); Config configFile = getConfig(file); OutputInfoFactory.get().setConfig(configFile); System.setProperty("textdb.allow_full_path", "true"); Connection c; try { boolean clean = false; if (args.length >= 2) { for (int i = 1; i < args.length; i++) { logger.logInfo("Arg " + i + ": " + args[i]); if (args[i].toLowerCase().equals("clean")) { clean = true; } } } dataFolder = new File(I_Constants.REPO_FOLDER); if (!dataFolder.exists()) { dataFolder.mkdirs(); } changedDate = true; changedPreviousDate = true; getParams(file); checkDates(); /*******************************/ // changedDate=false; // changedPreviousDate=false; /********************************/ if (clean || changedDate || changedPreviousDate) { logger.logInfo("Removing old data"); removeDBFolder(); removeRepoFolder(); removeReducedFolder(); changedDate = true; changedPreviousDate = true; } Class.forName("org.hsqldb.jdbcDriver"); logger.logInfo("Connecting to DB. This task can take several minutes... wait please."); c = DriverManager.getConnection("jdbc:hsqldb:file:" + I_Constants.DB_FOLDER, "sa", "sa"); initFileProviders(file); // OutputInfoFactory.get().getStatisticProcess().setOutputFolder(I_Constants.STATS_OUTPUT_FOLDER); /*******************************/ // DbSetup dbs=new DbSetup(c); // dbs.recreatePath("org/ihtsdo/statistics/db/setup/storedprocedure"); // dbs=null; /*******************************/ ImportManager impor = new ImportManager(c, file, changedDate, changedPreviousDate); impor.execute(); impor = null; Processor proc = new Processor(c, file); proc.execute(); proc = null; msg = logger.endTime(start); posIni = msg.indexOf("ProcessingTime:") + 16; OutputInfoFactory.get().getStatisticProcess().setTimeTaken(msg.substring(posIni)); // OutputInfoFactory.get().getPatternProcess().setOutputFolder(I_Constants.PATTERN_OUTPUT_FOLDER); long startPattern = logger.startTime(); PatternExecutor pe = new PatternExecutor(file); pe.execute(); pe = null; msg = logger.endTime(startPattern); posIni = msg.indexOf("ProcessingTime:") + 16; OutputInfoFactory.get().getPatternProcess().setTimeTaken(msg.substring(posIni)); OutputInfoFactory.get().setStatus("Complete"); } catch (Exception e) { OutputInfoFactory.get().setStatus("Error: " + e.getMessage() + " - View log for details."); e.printStackTrace(); } msg = logger.endTime(start); posIni = msg.indexOf("ProcessingTime:") + 16; OutputInfoFactory.get().setTimeTaken(msg.substring(posIni)); try { saveInfo(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.moviejukebox.MovieJukebox.java
public static void main(String[] args) throws Throwable { JukeboxStatistics.setTimeStart(System.currentTimeMillis()); // Create the log file name here, so we can change it later (because it's locked System.setProperty("file.name", LOG_FILENAME); PropertyConfigurator.configure("properties/log4j.properties"); LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion()); LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length())); LOG.info("https://github.com/YAMJ/yamj-v2"); LOG.info("Copyright (c) 2004-2016 YAMJ Members"); LOG.info(""); LOG.info("This software is licensed under the GNU General Public License v3+"); LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License"); LOG.info(""); LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : ""); LOG.info(" Commit Date: {}", GIT.getCommitTime()); LOG.info(" Build Date: {}", GIT.getBuildTime()); LOG.info(""); LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion()); LOG.info(""); if (!SystemTools.validateInstallation()) { LOG.info("ABORTING."); return;/*from ww w . ja va2 s . c o m*/ } String movieLibraryRoot = null; String jukeboxRoot = null; Map<String, String> cmdLineProps = new LinkedHashMap<>(); try { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-v".equalsIgnoreCase(arg)) { // We've printed the version, so quit now return; } else if ("-t".equalsIgnoreCase(arg)) { String pin = args[++i]; // load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // authorize to Trakt.TV TraktTV.getInstance().initialize().authorizeWithPin(pin); // We've authorized access to Trakt.TV, so quit now return; } else if ("-o".equalsIgnoreCase(arg)) { jukeboxRoot = args[++i]; PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot); } else if ("-c".equalsIgnoreCase(arg)) { jukeboxClean = Boolean.TRUE; PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE); } else if ("-k".equalsIgnoreCase(arg)) { setJukeboxPreserve(Boolean.TRUE); } else if ("-p".equalsIgnoreCase(arg)) { userPropertiesName = args[++i]; } else if ("-i".equalsIgnoreCase(arg)) { skipIndexGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE); } else if ("-h".equalsIgnoreCase(arg)) { skipHtmlGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE); } else if ("-dump".equalsIgnoreCase(arg)) { dumpLibraryStructure = Boolean.TRUE; } else if ("-memory".equalsIgnoreCase(arg)) { showMemory = Boolean.TRUE; PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE); } else if (arg.startsWith("-D")) { String propLine = arg.length() > 2 ? arg.substring(2) : args[++i]; int propDiv = propLine.indexOf('='); if (-1 != propDiv) { cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1)); } } else if (arg.startsWith("-")) { help(); return; } else { movieLibraryRoot = args[i]; } } } catch (Exception error) { LOG.error("Wrong arguments specified"); help(); return; } // Save the name of the properties file for use later setProperty("userPropertiesName", userPropertiesName); LOG.info("Processing started at {}", new Date()); LOG.info(""); // Load the moviejukebox-default.properties file if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) { return; } // Load the user properties file "moviejukebox.properties" // No need to abort if we don't find this file // Must be read before the skin, because this may contain an override skin setPropertiesStreamName(userPropertiesName, Boolean.FALSE); // Grab the skin from the command-line properties if (cmdLineProps.containsKey(SKIN_DIR)) { setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR)); } // Load the skin.properties file if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) { return; } // Load the skin-user.properties file (ignore the error) setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE); // Load the overlay.properties file (ignore the error) String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN); overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE) ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator) : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : ""); setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE); // Load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // This is needed to update the static reference for the API Keys in the pattern formatter // because the formatter is initialised before the properties files are read FilteringLayout.addApiKeys(); // Load the rest of the command-line properties for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) { setProperty(propEntry.getKey(), propEntry.getValue()); } // Read the information about the skin SkinProperties.readSkinVersion(); // Display the information about the skin SkinProperties.printSkinVersion(); StringBuilder properties = new StringBuilder("{"); for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) { properties.append(propEntry.getKey()); properties.append("="); properties.append(propEntry.getValue()); properties.append(","); } properties.replace(properties.length() - 1, properties.length(), "}"); // Print out the properties to the log file. LOG.debug("Properties: {}", properties.toString()); // Check for mjb.skipIndexGeneration and set as necessary // This duplicates the "-i" functionality, but allows you to have it in the property file skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE); if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) { peopleScan = Boolean.TRUE; peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE); peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10); popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5); // Issue 1947: Cast enhancement - option to save all related files to a specific folder peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", ""); if (isNotValidString(peopleFolder)) { peopleFolder = ""; } else if (!peopleFolder.endsWith(File.separator)) { peopleFolder += File.separator; } StringTokenizer st = new StringTokenizer( PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| "); while (st.hasMoreTokens()) { PHOTO_EXTENSIONS.add(st.nextToken()); } } // Check for mjb.skipHtmlGeneration and set as necessary // This duplicates the "-h" functionality, but allows you to have it in the property file skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE); // Look for the parameter in the properties file if it's not been set on the command line // This way we don't overwrite the setting if it's not found and defaults to FALSE showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE); // This duplicates the "-c" functionality, but allows you to have it in the property file jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE); MovieFilenameScanner.setSkipKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE)); MovieFilenameScanner.setSkipRegexKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE)); MovieFilenameScanner.setExtrasKeywords( tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| ")); MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray( getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"), ",;|")); MovieFilenameScanner.setLanguageDetection( PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE)); final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null); if (!languages.isEmpty()) { MovieFilenameScanner.clearLanguages(); for (String lang : languages.getKeywords()) { String values = languages.get(lang); if (values != null) { MovieFilenameScanner.addLanguage(lang, values, values); } else { LOG.info("No values found for language code '{}'", lang); } } } final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords", "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV"); MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords); String temp = getProperty("sorting.strip.prefixes"); if (temp != null) { StringTokenizer st = new StringTokenizer(temp, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("\"") && token.endsWith("\"")) { token = token.substring(1, token.length() - 1); } Movie.addSortIgnorePrefixes(token.toLowerCase()); } } enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE); enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE); enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE); // Check to see if don't have a root, check the property file if (StringTools.isNotValidString(movieLibraryRoot)) { movieLibraryRoot = getProperty("mjb.libraryRoot"); if (StringTools.isValidString(movieLibraryRoot)) { LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot); } else { LOG.error("No library root found!"); help(); return; } } if (jukeboxRoot == null) { jukeboxRoot = getProperty("mjb.jukeboxRoot"); if (jukeboxRoot == null) { LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors."); } else { LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot); } } File f = new File(movieLibraryRoot); if (f.exists() && f.isDirectory() && jukeboxRoot == null) { jukeboxRoot = movieLibraryRoot; } if (movieLibraryRoot == null) { help(); return; } if (jukeboxRoot == null) { LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !"); help(); return; } if (!f.exists()) { LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot); return; } FileTools.initUnsafeChars(); FileTools.initSubtitleExtensions(); // make canonical names jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot); movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot); MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot); if (dumpLibraryStructure) { LOG.warn( "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated"); ml.makeDumpStructure(); } else { ml.generateLibrary(); } // Now rename the log files renameLogFile(); if (ScanningLimit.isLimitReached()) { LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.", ScanningLimit.getLimit()); System.exit(EXIT_SCAN_LIMIT); } else { System.exit(EXIT_NORMAL); } }
From source file:com.netscape.cms.servlet.test.DRMTest.java
public static void main(String args[]) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, IOException { String host = null;/*from w w w. java 2s.co m*/ String port = null; String token_pwd = null; String db_dir = "./"; String protocol = "http"; String clientCertNickname = "KRA Administrator of Instance pki-kra's SjcRedhat Domain ID"; // parse command line arguments Options options = new Options(); options.addOption("h", true, "Hostname of the DRM"); options.addOption("p", true, "Port of the DRM"); options.addOption("w", true, "Token password"); options.addOption("d", true, "Directory for tokendb"); options.addOption("s", true, "Attempt Optional Secure SSL connection"); options.addOption("c", true, "Optional SSL Client cert Nickname"); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); } else { System.err.println("Error: no hostname provided."); usage(options); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } else { System.err.println("Error: no port provided"); usage(options); } if (cmd.hasOption("w")) { token_pwd = cmd.getOptionValue("w"); } else { System.err.println("Error: no token password provided"); usage(options); } if (cmd.hasOption("d")) { db_dir = cmd.getOptionValue("d"); } if (cmd.hasOption("s")) { if (cmd.getOptionValue("s") != null && cmd.getOptionValue("s").equals("true")) { protocol = "https"; } } if (cmd.hasOption("c")) { String nick = cmd.getOptionValue("c"); if (nick != null && protocol.equals("https")) { clientCertNickname = nick; } } } catch (ParseException e) { System.err.println("Error in parsing command line options: " + e.getMessage()); usage(options); } // used for crypto operations byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; try { iv = genIV(8); } catch (Exception e) { log("Can't generate initialization vector use default: " + e.toString()); } // used for wrapping to send data to DRM String transportCert = null; // Data to be archived SymmetricKey vek = null; String passphrase = null; // Session keys and passphrases for recovery SymmetricKey sessionKey = null; byte[] wrappedRecoveryKey = null; String recoveryPassphrase = null; byte[] wrappedRecoveryPassphrase = null; // retrieved data (should match archived data) byte[] encryptedData = null; String recoveredKey = null; // various ids used in recovery/archival operations KeyId keyId = null; String clientKeyId = null; RequestId recoveryRequestId = null; // Variables for data structures from calls KeyRequestResponse requestResponse = null; Key keyData = null; KeyInfo keyInfo = null; // Initialize token try { CryptoManager.initialize(db_dir); } catch (AlreadyInitializedException e) { // it is ok if it is already initialized } catch (Exception e) { log("INITIALIZATION ERROR: " + e.toString()); System.exit(1); } // Set base URI and get client KRAClient client; SystemCertClient systemCertClient; KeyClient keyClient; NSSCryptoProvider nssCrypto; try { ClientConfig config = new ClientConfig(); config.setServerURI(protocol + "://" + host + ":" + port + "/kra"); config.setCertNickname(clientCertNickname); config.setCertDatabase(db_dir); config.setCertPassword(token_pwd); nssCrypto = new NSSCryptoProvider(config); client = new KRAClient(new PKIClient(config, nssCrypto)); systemCertClient = (SystemCertClient) client.getClient("systemcert"); keyClient = (KeyClient) client.getClient("key"); } catch (Exception e) { e.printStackTrace(); return; } // Test 1: Get transport certificate from DRM transportCert = systemCertClient.getTransportCert().getEncoded(); transportCert = transportCert.substring(CertData.HEADER.length(), transportCert.indexOf(CertData.FOOTER)); keyClient.setTransportCert(transportCert); log("Transport Cert retrieved from DRM: " + transportCert); // Test 2: Get list of completed key archival requests log("\n\nList of completed archival requests"); KeyRequestInfoCollection list = keyClient.listRequests("complete", "securityDataEnrollment"); if (list.getTotal() == 0) { log("No requests found"); } else { Iterator<KeyRequestInfo> iter = list.getEntries().iterator(); while (iter.hasNext()) { KeyRequestInfo info = iter.next(); printRequestInfo(info); } } // Test 3: Get list of key recovery requests log("\n\nList of completed recovery requests"); KeyRequestInfoCollection list2 = keyClient.listRequests("complete", "securityDataRecovery"); if (list2.getTotal() == 0) { log("No requests found"); } else { Iterator<KeyRequestInfo> iter2 = list2.getEntries().iterator(); while (iter2.hasNext()) { KeyRequestInfo info = iter2.next(); printRequestInfo(info); } } // Test 4: Generate and archive a symmetric key log("Archiving symmetric key"); clientKeyId = "UUID: 123-45-6789 VEK " + Calendar.getInstance().getTime().toString(); try { vek = nssCrypto.generateSessionKey(); byte[] encoded = nssCrypto.createPKIArchiveOptions(transportCert, vek, null, KeyRequestResource.DES3_ALGORITHM, 0, iv); KeyRequestResponse info = keyClient.archivePKIOptions(clientKeyId, KeyRequestResource.SYMMETRIC_KEY_TYPE, KeyRequestResource.DES3_ALGORITHM, 0, encoded); log("Archival Results:"); printRequestInfo(info.getRequestInfo()); keyId = info.getKeyId(); } catch (Exception e) { log("Exception in archiving symmetric key:" + e.getMessage()); e.printStackTrace(); } //Test 5: Get keyId for active key with client ID log("Getting key ID for symmetric key"); keyInfo = keyClient.getActiveKeyInfo(clientKeyId); printKeyInfo(keyInfo); KeyId keyId2 = keyInfo.getKeyId(); if (keyId2 == null) { log("No archived key found"); } else { log("Archived Key found: " + keyId); } if (!keyId.equals(keyId2)) { log("Error: key ids from search and archival do not match"); } else { log("Success: keyids from search and archival match."); } // Test 6: Submit a recovery request for the symmetric key using a session key log("Submitting a recovery request for the symmetric key using session key"); try { sessionKey = nssCrypto.generateSessionKey(); wrappedRecoveryKey = CryptoUtil.wrapSymmetricKey(nssCrypto.getManager(), nssCrypto.getToken(), transportCert, sessionKey); keyData = keyClient.retrieveKey(keyId, wrappedRecoveryKey); } catch (Exception e) { log("Exception in recovering symmetric key using session key: " + e.getMessage()); } encryptedData = keyData.getEncryptedData(); try { recoveredKey = Utils.base64encode(nssCrypto.unwrapWithSessionKey(encryptedData, sessionKey, KeyRequestResource.DES3_ALGORITHM, keyData.getNonceData())); } catch (Exception e) { log("Exception in unwrapping key: " + e.toString()); e.printStackTrace(); } if (!recoveredKey.equals(Utils.base64encode(vek.getEncoded()))) { log("Error: recovered and archived keys do not match!"); } else { log("Success: recoverd and archived keys match!"); } // Test 7: Submit a recovery request for the symmetric key using a passphrase log("Submitting a recovery request for the symmetric key using a passphrase"); recoveryPassphrase = "Gimme me keys please"; try { sessionKey = nssCrypto.generateSessionKey(); wrappedRecoveryPassphrase = nssCrypto.wrapWithSessionKey(recoveryPassphrase, iv, sessionKey, KeyRequestResource.DES3_ALGORITHM); wrappedRecoveryKey = nssCrypto.wrapSessionKeyWithTransportCert(sessionKey, transportCert); keyData = keyClient.retrieveKeyUsingWrappedPassphrase(keyId, wrappedRecoveryKey, wrappedRecoveryPassphrase, iv); } catch (Exception e) { log("Exception in recovering symmetric key using passphrase" + e.toString()); e.printStackTrace(); } encryptedData = keyData.getEncryptedData(); try { recoveredKey = Utils.base64encode(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase)); } catch (Exception e) { log("Error: unable to unwrap key using passphrase"); e.printStackTrace(); } if (recoveredKey == null || !recoveredKey.equals(Utils.base64encode(vek.getEncoded()))) { log("Error: recovered and archived keys do not match!"); } else { log("Success: recovered and archived keys do match!"); } passphrase = "secret12345"; // Test 8: Generate and archive a passphrase clientKeyId = "UUID: 123-45-6789 RKEK " + Calendar.getInstance().getTime().toString(); try { requestResponse = keyClient.archivePassphrase(clientKeyId, passphrase); log("Archival Results:"); printRequestInfo(requestResponse.getRequestInfo()); keyId = requestResponse.getKeyId(); } catch (Exception e) { log("Exception in archiving symmetric key:" + e.toString()); e.printStackTrace(); } //Test 9: Get keyId for active passphrase with client ID log("Getting key ID for passphrase"); keyInfo = keyClient.getActiveKeyInfo(clientKeyId); printKeyInfo(keyInfo); keyId2 = keyInfo.getKeyId(); if (keyId2 == null) { log("No archived key found"); } else { log("Archived Key found: " + keyId); } if (!keyId.equals(keyId2)) { log("Error: key ids from search and archival do not match"); } else { log("Success: key ids from search and archival do match!"); } // Test 10: Submit a recovery request for the passphrase using a session key log("Submitting a recovery request for the passphrase using session key"); sessionKey = null; wrappedRecoveryKey = null; try { keyData = keyClient.retrieveKeyByPassphrase(keyId, recoveryPassphrase); } catch (Exception e) { log("Exception in recovering passphrase using session key: " + e.getMessage()); } encryptedData = keyData.getEncryptedData(); try { recoveredKey = new String(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase), "UTF-8"); } catch (Exception e) { log("Exception in unwrapping key: " + e.toString()); e.printStackTrace(); } if (recoveredKey == null || !recoveredKey.equals(passphrase)) { log("Error: recovered and archived passphrases do not match!"); } else { log("Success: recovered and archived passphrases do match!"); } // Test 11: Submit a recovery request for the passphrase using a passphrase try { sessionKey = nssCrypto.generateSessionKey(); wrappedRecoveryKey = nssCrypto.wrapSessionKeyWithTransportCert(sessionKey, transportCert); wrappedRecoveryPassphrase = nssCrypto.wrapWithSessionKey(recoveryPassphrase, iv, sessionKey, KeyRequestResource.DES3_ALGORITHM); keyData = keyClient.retrieveKeyUsingWrappedPassphrase(keyId, wrappedRecoveryKey, wrappedRecoveryPassphrase, iv); } catch (Exception e1) { e1.printStackTrace(); System.out.println("Test 17: " + e1.getMessage()); System.exit(-1); } encryptedData = keyData.getEncryptedData(); try { recoveredKey = new String(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase), "UTF-8"); } catch (Exception e) { log("Error: cannot unwrap key using passphrase"); e.printStackTrace(); } if (recoveredKey == null || !recoveredKey.equals(passphrase)) { log("Error: recovered and archived passphrases do not match!"); } else { log("Success: recovered and archived passphrases do match!"); } // Test 12: Get key log("Getting passphrase: " + keyId); try { keyData = keyClient.retrieveKeyByPassphrase(keyId, recoveryPassphrase); } catch (Exception e1) { e1.printStackTrace(); } encryptedData = keyData.getEncryptedData(); try { recoveredKey = new String(nssCrypto.unwrapWithPassphrase(encryptedData, recoveryPassphrase), "UTF-8"); } catch (Exception e) { log("Error: Can't unwrap recovered key using passphrase"); e.printStackTrace(); } if (recoveredKey == null || !recoveredKey.equals(passphrase)) { log("Error: recovered and archived passphrases do not match!"); } else { log("Success: recovered and archived passphrases do match!"); } // Test 13: Get non-existent request RequestId requestId = new RequestId("0xabcdef"); log("Getting non-existent request: " + requestId.toHexString()); try { keyClient.getRequestInfo(requestId); log("Error: getting non-existent request does not throw an exception"); } catch (RequestNotFoundException e) { log("Success: getting non-existent request throws an exception: " + e.getMessage() + " (" + e.getRequestId().toHexString() + ")"); } // Test 14: Request x509 key recovery // This test requires to retrieve keyId and matching certificate // from installed instances of CA and DRM String keyID = "1"; String b64Certificate = "MIIC+TCCAeGgAwIBAgIBDDANBgkqhkiG9w0BAQsFADBOMSswKQYDVQQKDCJ1c2Vy" + "c3lzLnJlZGhhdC5jb20gU2VjdXJpdHkgRG9tYWluMR8wHQYDVQQDDBZDQSBTaWdu" + "aW5nIENlcnRpZmljYXRlMB4XDTEzMTAyNTE5MzQwM1oXDTE0MDQyMzE5MzQwM1ow" + "EzERMA8GCgmSJomT8ixkAQEMAXgwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB" + "ALhLfGmKvxFsKXPh49q1QsluXU3WlyS1XnpDLgOAhgTNgO4sG6CpPdv6hZYIvQBb" + "ZQ5bhuML+NXK+Q+EIiNk1cUTxgL3a30sPzy6QaFWxwM8i4uXm4nCBYv7T+n4V6/O" + "xHIM2Ch/dviAb3vz+M9trErv9t+d2H8jNXT3sHuDb/kvAgMBAAGjgaAwgZ0wHwYD" + "VR0jBBgwFoAUh1cxWFRY+nMsx4odQQI1GqyFxP8wSwYIKwYBBQUHAQEEPzA9MDsG" + "CCsGAQUFBzABhi9odHRwOi8vZG9ndGFnMjAudXNlcnN5cy5yZWRoYXQuY29tOjgw" + "ODAvY2Evb2NzcDAOBgNVHQ8BAf8EBAMCBSAwHQYDVR0lBBYwFAYIKwYBBQUHAwIG" + "CCsGAQUFBwMEMA0GCSqGSIb3DQEBCwUAA4IBAQCvmbUzQOouE2LgQQcKfmgwwJMJ" + "9tMrPwDUtyFdaIFoPL4uZaujSscaN4IWK2r5vIMJ65jwYCI7sI9En2ZfO28J9dQj" + "lpqu6TaJ+xtaMk7OvXpVB7lJk73HAttMGjETlkoq/6EjxcugmJsDqVD0b2tO7Vd0" + "hroBe2uPDHM2ASewZF415lUcRh0URtmxSazTInbyxpmy1wgSJQ0C6fMCeT+hUFlA" + "0P4k1TIprapGVq7FpKcqlhK2gTBfTSnoO7gmXG/9MxJiYpb/Aph8ptXq6quHz1Mj" + "greWr3xTsy6gF2yphUEkGHh4v22XvK+FLx9Jb6zloMWA2GG9gpUpvMnl1fH4"; log("Requesting X509 key recovery."); recoveryRequestId = keyClient.recoverKey(new KeyId(keyID), null, null, null, b64Certificate) .getRequestInfo().getRequestId(); log("Requesting X509 key recovery request: " + recoveryRequestId); // Test 55: Approve x509 key recovery log("Approving X509 key recovery request: " + recoveryRequestId); keyClient.approveRequest(recoveryRequestId); // Test 16: Recover x509 key log("Recovering X509 key based on request: " + recoveryRequestId); try { // KeyData recoveredX509Key = client.recoverKey(recoveryRequestId, "netscape"); // log("Success: X509Key recovered: "+ recoveredX509Key.getP12Data()); } catch (RequestNotFoundException e) { log("Error: recovering X509Key"); } // Test 1: Get transport certificate from DRM transportCert = systemCertClient.getTransportCert().getEncoded(); transportCert = transportCert.substring(CertData.HEADER.length(), transportCert.indexOf(CertData.FOOTER)); log("Transport Cert retrieved from DRM: " + transportCert); // Test 17: Get list of completed key archival requests log("\n\nList of completed archival requests"); list = keyClient.listRequests("complete", IRequest.SYMKEY_GENERATION_REQUEST); if (list.getTotal() == 0) { log("No requests found"); } else { Iterator<KeyRequestInfo> iter = list.getEntries().iterator(); while (iter.hasNext()) { KeyRequestInfo info = iter.next(); printRequestInfo(info); } } // test 18: Generate symmetric key clientKeyId = "Symmetric Key #1234f " + Calendar.getInstance().getTime().toString(); List<String> usages = new ArrayList<String>(); usages.add(SymKeyGenerationRequest.DECRYPT_USAGE); usages.add(SymKeyGenerationRequest.ENCRYPT_USAGE); KeyRequestResponse genKeyResponse = keyClient.generateSymmetricKey(clientKeyId, KeyRequestResource.AES_ALGORITHM, 128, usages, null); printRequestInfo(genKeyResponse.getRequestInfo()); keyId = genKeyResponse.getKeyId(); // test 19: Get keyId for active key with client ID log("Getting key ID for symmetric key"); keyInfo = keyClient.getActiveKeyInfo(clientKeyId); printKeyInfo(keyInfo); keyId2 = keyInfo.getKeyId(); if (keyId2 == null) { log("No archived key found"); } else { log("Archived Key found: " + keyId); } if (!keyId.equals(keyId2)) { log("Error: key ids from search and archival do not match"); } else { log("Success: keyids from search and archival match."); } // Test 20: Submit a recovery request for the symmetric key using a session key log("Submitting a recovery request for the symmetric key using session key"); try { sessionKey = nssCrypto.generateSessionKey(); wrappedRecoveryKey = nssCrypto.wrapSessionKeyWithTransportCert(sessionKey, transportCert); keyData = keyClient.retrieveKey(keyId, wrappedRecoveryKey); } catch (Exception e) { log("Exception in recovering symmetric key using session key: " + e.getMessage()); } encryptedData = keyData.getEncryptedData(); try { recoveredKey = new String(nssCrypto.unwrapWithSessionKey(encryptedData, sessionKey, KeyRequestResource.DES3_ALGORITHM, keyData.getNonceData())); } catch (Exception e) { log("Exception in unwrapping key: " + e.toString()); e.printStackTrace(); } // test 21: Generate symmetric key - invalid algorithm try { genKeyResponse = keyClient.generateSymmetricKey("Symmetric Key #1235", "AFS", 128, usages, null); } catch (Exception e) { log("Exception: " + e); } // test 22: Generate symmetric key - invalid key size try { genKeyResponse = keyClient.generateSymmetricKey("Symmetric Key #1236", "AES", 0, usages, null); } catch (Exception e) { log("Exception: " + e); } // test 23: Generate symmetric key - usages not defined try { genKeyResponse = keyClient.generateSymmetricKey("Symmetric Key #1236", "DES", 56, null, null); } catch (Exception e) { log("Exception: " + e); } // Test 24: Generate and archive a symmetric key of type AES log("Archiving symmetric key"); clientKeyId = "UUID: 123-45-6789 VEK " + Calendar.getInstance().getTime().toString(); try { vek = nssCrypto.generateSymmetricKey(KeyRequestResource.AES_ALGORITHM, 128); byte[] encoded = CryptoUtil.createPKIArchiveOptions(nssCrypto.getManager(), nssCrypto.getToken(), transportCert, vek, null, KeyGenAlgorithm.DES3, 0, new IVParameterSpec(iv)); KeyRequestResponse response = keyClient.archivePKIOptions(clientKeyId, KeyRequestResource.SYMMETRIC_KEY_TYPE, KeyRequestResource.AES_ALGORITHM, 128, encoded); log("Archival Results:"); printRequestInfo(response.getRequestInfo()); keyId = response.getKeyId(); } catch (Exception e) { log("Exception in archiving symmetric key:" + e.getMessage()); e.printStackTrace(); } //Test 25: Get keyId for active key with client ID log("Getting key ID for symmetric key"); keyInfo = keyClient.getActiveKeyInfo(clientKeyId); printKeyInfo(keyInfo); keyId2 = keyInfo.getKeyId(); if (keyId2 == null) { log("No archived key found"); } else { log("Archived Key found: " + keyId); } if (!keyId.equals(keyId2)) { log("Error: key ids from search and archival do not match"); } else { log("Success: keyids from search and archival match."); } // Test 26: Submit a recovery request for the symmetric key log("Submitting a recovery request for the symmetric key without using session key"); try { keyData = keyClient.retrieveKey(keyId); } catch (Exception e) { log("Exception in recovering symmetric key using session key: " + e.getMessage()); } // Since no session key is provided externally, the retrieveKey method // generates a session key, wraps it with transport cert and completes the request. // The encrypted data is then unwrapped using the temporary session key and set to // the attribute privateData. recoveredKey = Utils.base64encode(keyData.getData()); if (!recoveredKey.equals(Utils.base64encode(vek.getEncoded()))) { log("Error: recovered and archived keys do not match!"); } else { log("Success: recoverd and archived keys match!"); } // Test 27: Get key info log("getting key info for existing key"); printKeyInfo(keyClient.getKeyInfo(keyId)); //Test 28: Modify status log("modify the key status"); keyClient.modifyKeyStatus(keyId, KeyResource.KEY_STATUS_INACTIVE); keyInfo = keyClient.getKeyInfo(keyId); printKeyInfo(keyInfo); //Test 29: Confirm no more active keys with this ID log("look for active keys with this id"); clientKeyId = keyInfo.getClientKeyID(); try { keyInfo = keyClient.getActiveKeyInfo(clientKeyId); printKeyInfo(keyInfo); } catch (ResourceNotFoundException e) { log("Success: ResourceNotFound exception thrown: " + e); } // Test asymmetric key generation. String[] algs = { "RSA", "DSA" }; for (int i = 0; i < algs.length; i++) { // Test 30: Generate Asymmetric keys - RSA key System.out.println("\nTesting asymmetric key generation for algorithm " + algs[i]); clientKeyId = "AsymKey #" + Calendar.getInstance().getTimeInMillis(); usages.clear(); usages.add(AsymKeyGenerationRequest.SIGN); usages.add(AsymKeyGenerationRequest.VERIFY); KeyRequestResponse response = keyClient.generateAsymmetricKey(clientKeyId, algs[i], 1024, usages, null); printRequestInfo(response.getRequestInfo()); System.out.println(); // Test 31: Get information of the newly generated asymmetric keys System.out.println("Fetch information of the newly generated asymmetric keys."); System.out.println(); KeyInfo info = keyClient.getKeyInfo(response.getKeyId()); printKeyInfo(info); System.out.println(); // Test 32: Retrieve private key data System.out.println("Retrieving and verifying the generated private key."); try { keyData = keyClient.retrieveKey(response.getKeyId()); } catch (Exception e) { log("Exception retrieving the private key data."); e.printStackTrace(); } // Test 33: Verify the generated key pair. if (isKeyPairValid(algs[i], keyData.getData(), info.getPublicKey())) { log("The key pair generated using " + algs[i] + " algorithm is valid."); } else { log("The key pair generated using " + algs[i] + " algorithm is invalid."); } System.out.println(); } // Test 34: }
From source file:net.sf.extjwnl.cli.ewn.java
public static void main(String[] args) throws IOException, JWNLException { if (args.length < 1) { System.out.println(USAGE); System.exit(0);// w w w. j a va2 s. c o m } //find dictionary Dictionary d = null; File config = new File(defaultConfig); if (!config.exists()) { if (System.getenv().containsKey("WNHOME")) { String wnHomePath = System.getenv().get("WNHOME"); File wnHome = new File(wnHomePath); if (wnHome.exists()) { d = Dictionary.getFileBackedInstance(wnHomePath); } else { log.error("Cannot find dictionary. Make sure " + defaultConfig + " is available or WNHOME variable is set."); } } } else { d = Dictionary.getInstance(new FileInputStream(config)); } if (null != d) { //parse and execute command line if ((-1 < args[0].indexOf('%') && -1 < args[0].indexOf(':')) || "-script".equals(args[0]) || (-1 < args[0].indexOf('#'))) { d.edit(); //edit if ("-script".equals(args[0])) { if (args.length < 2) { log.error("Filename missing for -script command"); System.exit(1); } else { File script = new File(args[1]); if (script.exists()) { //load into args ArrayList<String> newArgs = new ArrayList<String>(); BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(script), "UTF-8")); try { String str; while ((str = in.readLine()) != null) { String[] bits = str.split(" "); StringBuilder tempArg = null; for (String bit : bits) { int quoteCnt = 0; for (int j = 0; j < bit.length(); j++) { if ('"' == bit.charAt(j)) { quoteCnt++; } } if (null != tempArg) { if (0 == quoteCnt) { tempArg.append(" ").append(bit); } else { tempArg.append(" ").append(bit.replaceAll("\"\"", "\"")); if (1 == (quoteCnt % 2)) { newArgs.add( tempArg.toString().substring(1, tempArg.length() - 1)); tempArg = null; } } } else { if (0 == quoteCnt) { newArgs.add(bit); } else { if (1 == (quoteCnt % 2)) { tempArg = new StringBuilder(bit.replaceAll("\"\"", "\"")); } else { newArgs.add(bit.replaceAll("\"\"", "\"")); } } } } if (null != tempArg) { newArgs.add(tempArg.toString()); } } } finally { try { in.close(); } catch (IOException e) { //nop } } args = newArgs.toArray(args); } } } Word workWord = null; String key = null; String lemma = null; int lexFileNum = -1; int lexId = -1; // String headLemma = null; // int headLexId = -1; POS pos = null; String derivation = null; for (int i = 0; i < args.length; i++) { if (null == key && '-' != args[i].charAt(0) && ((-1 < args[i].indexOf('%') && -1 < args[i].indexOf(':')))) { key = args[i]; log.info("Searching " + key + "..."); if (null != key) { workWord = d.getWordBySenseKey(key); } if (null == workWord) { //parse sensekey lemma = key.substring(0, key.indexOf('%')).replace('_', ' '); String posId = key.substring(key.indexOf('%') + 1, key.indexOf(':')); if ("1".equals(posId) || "2".equals(posId) || "3".equals(posId) || "4".equals(posId) || "5".equals(posId)) { pos = POS.getPOSForId(Integer.parseInt(posId)); String lexFileString = key.substring(key.indexOf(':') + 1); if (-1 < lexFileString.indexOf(':')) { lexFileNum = Integer .parseInt(lexFileString.substring(0, lexFileString.indexOf(':'))); if (lexFileString.indexOf(':') + 1 < lexFileString.length()) { String lexIdString = lexFileString .substring(lexFileString.indexOf(':') + 1); if (-1 < lexIdString.indexOf(':')) { lexId = Integer .parseInt(lexIdString.substring(0, lexIdString.indexOf(':'))); // if (lexIdString.indexOf(':') + 1 < lexIdString.length()) { // headLemma = lexIdString.substring(lexIdString.indexOf(':') + 1); // if (-1 < headLemma.indexOf(':')) { // headLemma = headLemma.substring(0, headLemma.indexOf(':')); // if (null != headLemma && !"".equals(headLemma) && lexIdString.lastIndexOf(':') + 1 < lexIdString.length()) { // headLexId = Integer.parseInt(lexIdString.substring(lexIdString.lastIndexOf(':') + 1)); // } // } else { // log.error("Malformed sensekey " + key); // System.exit(1); // } // } } else { log.error("Malformed sensekey " + key); System.exit(1); } } else { log.error("Malformed sensekey " + key); System.exit(1); } } else { log.error("Malformed sensekey " + key); System.exit(1); } } else { log.error("Malformed sensekey " + key); System.exit(1); } } } else if (-1 < args[i].indexOf('#')) { if (2 < args[i].length()) { derivation = args[i].substring(2); if (null == derivation) { log.error("Missing derivation"); System.exit(1); } else { pos = POS.getPOSForKey(args[i].substring(0, 1)); if (null == pos) { log.error("POS " + args[i] + " is not recognized for derivation " + derivation); System.exit(1); } } } } if ("-add".equals(args[i])) { if (null == key) { log.error("Missing sensekey"); System.exit(1); } if (null != workWord) { log.error("Duplicate sensekey " + workWord.getSenseKey()); System.exit(1); } log.info("Creating " + pos.getLabel() + " synset..."); Synset tempSynset = d.createSynset(pos); log.info("Creating word " + lemma + "..."); workWord = new Word(d, tempSynset, 1, lemma); workWord.setLexId(lexId); tempSynset.getWords().add(workWord); tempSynset.setLexFileNum(lexFileNum); key = null; } if ("-remove".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { d.removeSynset(workWord.getSynset()); workWord = null; key = null; } } if ("-addword".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { Word tempWord = new Word(d, workWord.getSynset(), workWord.getSynset().getWords().size() + 1, args[i]); workWord.getSynset().getWords().add(tempWord); key = null; } else { log.error( "Missing word for addword command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-removeword".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { workWord.getSynset().getWords().remove(workWord); key = null; } } if ("-setgloss".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.getSynset().setGloss(args[i]); key = null; } else { log.error("Missing gloss for setgloss command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setadjclus".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.getSynset().setIsAdjectiveCluster(Boolean.parseBoolean(args[i])); key = null; } else { log.error("Missing flag for setadjclus command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setverbframe".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { if (workWord instanceof Verb) { Verb verb = (Verb) workWord; if ('-' == args[i].charAt(0)) { verb.getVerbFrameFlags().clear(Integer.parseInt(args[i].substring(1))); } else { verb.getVerbFrameFlags().set(Integer.parseInt(args[i])); } } else { log.error("Word at " + workWord.getSenseKey() + " should be verb"); System.exit(1); } key = null; } else { log.error("Missing index for setverbframe command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setverbframeall".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { if (workWord.getSynset() instanceof VerbSynset) { if ('-' == args[i].charAt(0)) { workWord.getSynset().getVerbFrameFlags() .clear(Integer.parseInt(args[i].substring(1))); } else { workWord.getSynset().getVerbFrameFlags().set(Integer.parseInt(args[i])); } } else { log.error("Synset at " + workWord.getSenseKey() + " should be verb"); System.exit(1); } key = null; } else { log.error("Missing index for setverbframeall command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setlexfile".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { if (-1 < args[i].indexOf('.')) { workWord.getSynset() .setLexFileNum(LexFileNameLexFileIdMap.getMap().get(args[i])); } else { workWord.getSynset().setLexFileNum(Integer.parseInt(args[i])); } } else { log.error("Missing file number or name for setlexfile command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-addptr".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { Word targetWord = d.getWordBySenseKey(args[i]); if (null != targetWord) { i++; if (i < args.length) { PointerType pt = PointerType.getPointerTypeForKey(args[i]); if (null != pt) { Pointer p; if (pt.isLexical()) { p = new Pointer(pt, workWord, targetWord); } else { p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset()); } if (!workWord.getSynset().getPointers().contains(p)) { workWord.getSynset().getPointers().add(p); } else { log.error("Duplicate pointer of type " + pt + " to " + targetWord.getSenseKey() + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Invalid pointer type at " + args[i] + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing pointer type at " + args[i] + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing target at " + args[i] + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } key = null; } else { log.error("Missing sensekey for addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-removeptr".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { Word targetWord = d.getWordBySenseKey(args[i]); if (null != targetWord) { i++; if (i < args.length) { PointerType pt = PointerType.getPointerTypeForKey(args[i]); if (null != pt) { Pointer p; if (pt.isLexical()) { p = new Pointer(pt, workWord, targetWord); } else { p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset()); } if (workWord.getSynset().getPointers().contains(p)) { workWord.getSynset().getPointers().remove(p); } else { log.error("Missing pointer of type " + pt + " to " + targetWord.getSenseKey() + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Invalid pointer type at " + args[i] + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing pointer type at " + args[i] + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing target at " + args[i] + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } key = null; } else { log.error("Missing sensekey for removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setlexid".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.setLexId(Integer.parseInt(args[i])); key = null; } else { log.error("Missing lexid for setlexid command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setusecount".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.setUseCount(Integer.parseInt(args[i])); key = null; } else { log.error("Missing count for setusecount command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-addexc".equals(args[i])) { i++; if (i < args.length && '-' != args[i].charAt(0)) { String baseform = args[i]; Exc e = d.getException(pos, derivation); if (null != e) { if (null != e.getExceptions()) { if (!e.getExceptions().contains(baseform)) { e.getExceptions().add(baseform); } } } else { ArrayList<String> list = new ArrayList<String>(1); list.add(baseform); d.createException(pos, derivation, list); } derivation = null; } else { log.error("Missing baseform for addexc command for derivation " + derivation); System.exit(1); } } if ("-removeexc".equals(args[i])) { Exc e = d.getException(pos, derivation); if (null != e) { i++; if (i < args.length && '-' != args[i].charAt(0)) { String baseform = args[i]; if (null != e.getExceptions()) { if (e.getExceptions().contains(baseform)) { e.getExceptions().remove(baseform); } if (0 == e.getExceptions().size()) { d.removeException(e); } } } else { d.removeException(e); } } else { log.error("Missing derivation " + derivation); System.exit(1); } derivation = null; } } d.save(); } else { //browse String key = args[0]; if (1 == args.length) { for (POS pos : POS.getAllPOS()) { IndexWord iw = d.getIndexWord(pos, key); if (null == iw) { System.out.println("\nNo information available for " + pos.getLabel() + " " + key); } else { System.out.println( "\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma()); printAvailableInfo(iw); } if (null != d.getMorphologicalProcessor()) { List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key); if (null != forms) { for (String form : forms) { if (!key.equals(form)) { iw = d.getIndexWord(pos, form); if (null != iw) { System.out.println("\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma()); printAvailableInfo(iw); } } } } } } } else { boolean needHelp = false; boolean needGloss = false; boolean needLex = false; boolean needOffset = false; boolean needSenseNum = false; boolean needSenseKeys = false; int needSense = 0; for (String arg : args) { if ("-h".equals(arg)) { needHelp = true; } if ("-g".equals(arg)) { needGloss = true; } if ("-a".equals(arg)) { needLex = true; } if ("-o".equals(arg)) { needOffset = true; } if ("-s".equals(arg)) { needSenseNum = true; } if ("-k".equals(arg)) { needSenseKeys = true; } if (arg.startsWith("-n") && 2 < arg.length()) { needSense = Integer.parseInt(arg.substring(2)); } } for (String arg : args) { if (arg.startsWith("-ants") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display synsets containing direct antonyms of the search string.\n" + "\n" + "Direct antonyms are a pair of words between which there is an\n" + "associative bond built up by co-occurrences.\n" + "\n" + "Antonym synsets are preceded by \"=>\"."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nAntonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.ANTONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //ants if (arg.startsWith("-hype") && 6 == arg.length()) { if (needHelp) { System.out.println( "Recursively display hypernym (superordinate) tree for the search\n" + "string.\n" + "\n" + "Hypernym is the generic term used to designate a whole class of\n" + "specific instances. Y is a hypernym of X if X is a (kind of) Y.\n" + "\n" + "Hypernym synsets are preceded by \"=>\", and are indented from\n" + "the left according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHypernyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hype if (arg.startsWith("-hypo") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display immediate hyponyms (subordinates) for the search string.\n" + "\n" + "Hyponym is the generic term used to designate a member of a class.\n" + "X is a hyponym of Y if X is a (kind of) Y.\n" + "\n" + "Hyponym synsets are preceded by \"=>\"."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.HYPONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hypo if (arg.startsWith("-tree") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display hyponym (subordinate) tree for the search string. This is\n" + "a recursive search that finds the hyponyms of each hyponym. \n" + "\n" + "Hyponym is the generic term used to designate a member of a class.\n" + "X is a hyponym of Y if X is a (kind of) Y. \n" + "\n" + "Hyponym synsets are preceded by \"=>\", and are indented from the left\n" + "according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.HYPONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //tree if (arg.startsWith("-enta") && 6 == arg.length()) { if (needHelp) { System.out.println( "Recursively display entailment relations of the search string.\n" + "\n" + "The action represented by the verb X entails Y if X cannot be done\n" + "unless Y is, or has been, done.\n" + "\n" + "Entailment synsets are preceded by \"=>\", and are indented from the left\n" + "according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nEntailment of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.ENTAILMENT, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //enta if (arg.startsWith("-syns") && 6 == arg.length()) { POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nSynonyms of " + p.getLabel() + " " + iw.getLemma()); if (POS.ADJECTIVE == p) { if (needHelp) { System.out.println( "Display synonyms and synsets related to synsets containing\n" + "the search string. If the search string is in a head synset\n" + "the 'cluster's' satellite synsets are displayed. If the search\n" + "string is in a satellite synset, its head synset is displayed.\n" + "If the search string is a pertainym the word or synset that it\n" + "pertains to is displayed.\n" + "\n" + "A cluster is a group of adjective synsets that are organized around\n" + "antonymous pairs or triplets. An adjective cluster contains two or more\n" + "head synsets that contan antonyms. Each head synset has one or more\n" + "satellite synsets.\n" + "\n" + "A head synset contains at least one word that has a direct antonym\n" + "in another head synset of the same cluster.\n" + "\n" + "A satellite synset represents a concept that is similar in meaning to\n" + "the concept represented by its head synset.\n" + "\n" + "Direct antonyms are a pair of words between which there is an\n" + "associative bond built up by co-occurrences.\n" + "\n" + "Direct antonyms are printed in parentheses following the adjective.\n" + "The position of an adjective in relation to the noun may be restricted\n" + "to the prenominal, postnominal or predicative position. Where present\n" + "these restrictions are noted in parentheses.\n" + "\n" + "A pertainym is a relational adjective, usually defined by such phrases\n" + "as \"of or pertaining to\" and that does not have an antonym. It pertains\n" + "to a noun or another pertainym.\n" + "\n" + "Senses contained in head synsets are displayed above the satellites,\n" + "which are indented and preceded by \"=>\". Senses contained in\n" + "satellite synsets are displayed with the head synset below. The head\n" + "synset is preceded by \"=>\".\n" + "\n" + "Pertainym senses display the word or synsets that the search string\n" + "pertains to."); } tracePointers(iw, PointerType.SIMILAR_TO, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PARTICIPLE_OF, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } if (POS.ADVERB == p) { if (needHelp) { System.out.println( "Display synonyms and synsets related to synsets containing\n" + "the search string. If the search string is a pertainym the word\n" + "or synset that it pertains to is displayed.\n" + "\n" + "A pertainym is a relational adverb that is derived from an adjective.\n" + "\n" + "Pertainym senses display the word that the search string is derived from\n" + "and the adjective synset that contains the word. If the adjective synset\n" + "is a satellite synset, its head synset is also displayed."); } tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } if (POS.NOUN == p || POS.VERB == p) { if (needHelp) { System.out.println( "Recursively display hypernym (superordinate) tree for the search\n" + "string.\n" + "\n" + "Hypernym is the generic term used to designate a whole class of\n" + "specific instances. Y is a hypernym of X if X is a (kind of) Y.\n" + "\n" + "Hypernym synsets are preceded by \"=>\", and are indented from\n" + "the left according to their level in the hierarchy."); } tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } } //syns if (arg.startsWith("-smem") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMember Holonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //smem if (arg.startsWith("-ssub") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nSubstance Holonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //ssub if (arg.startsWith("-sprt") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nPart Holonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //sprt if (arg.startsWith("-memb") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMember Meronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //memb if (arg.startsWith("-subs") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nSubstance Meronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //subs if (arg.startsWith("-part") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nPart Meronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //part if (arg.startsWith("-mero") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //mero if (arg.startsWith("-holo") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //holo if (arg.startsWith("-caus") && 6 == arg.length()) { if (needHelp) { System.out.println("Recursively display CAUSE TO relations of the search string.\n" + "\n" + "The action represented by the verb X causes the action represented by\n" + "the verb Y.\n" + "\n" + "CAUSE TO synsets are preceded by \"=>\", and are indented from the left\n" + "according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\n'Cause to' of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.CAUSE, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //caus if (arg.startsWith("-pert") && 6 == arg.length()) { POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nPertainyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //pert if (arg.startsWith("-attr") && 6 == arg.length()) { POS p = POS.getPOSForKey(arg.substring(5)); if (needHelp) { if (POS.NOUN == p) { System.out .println("Display adjectives for which search string is an attribute."); } if (POS.ADJECTIVE == p) { System.out.println("Display nouns that are attributes of search string."); } } IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nAttributes of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.ATTRIBUTE, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //attr if (arg.startsWith("-deri") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display derived forms - nouns and verbs that are related morphologically.\n" + "Each related synset is preceeded by its part of speech. Each word in the\n" + "synset is followed by its sense number."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nDerived forms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.NOMINALIZATION, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //deri if (arg.startsWith("-domn") && 6 == arg.length()) { if (needHelp) { System.out.println("Display domain to which this synset belongs."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.CATEGORY, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.USAGE, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.REGION, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //domn if (arg.startsWith("-domt") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all synsets belonging to the domain."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.CATEGORY_MEMBER, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.USAGE_MEMBER, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.REGION_MEMBER, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //domt if (arg.startsWith("-faml") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display familiarity and polysemy information for the search string.\n" + "The polysemy count is the number of senses in WordNet."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { String[] freqs = { "extremely rare", "very rare", "rare", "uncommon", "common", "familiar", "very familiar", "extremely familiar" }; String[] pos = { "a noun", "a verb", "an adjective", "an adverb" }; int cnt = iw.getSenses().size(); int familiar = 0; if (cnt == 0) { familiar = 0; } if (cnt == 1) { familiar = 1; } if (cnt == 2) { familiar = 2; } if (cnt >= 3 && cnt <= 4) { familiar = 3; } if (cnt >= 5 && cnt <= 8) { familiar = 4; } if (cnt >= 9 && cnt <= 16) { familiar = 5; } if (cnt >= 17 && cnt <= 32) { familiar = 6; } if (cnt > 32) { familiar = 7; } System.out.println("\n" + iw.getLemma() + " used as " + pos[p.getId() - 1] + " is " + freqs[familiar] + " (polysemy count = " + cnt + ")"); } } //faml if (arg.startsWith("-fram") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display applicable verb sentence frames for the search string.\n" + "\n" + "A frame is a sentence template illustrating the usage of a verb.\n" + "\n" + "Verb sentence frames are preceded with the string \"*>\" if a sentence\n" + "frame is acceptable for all of the words in the synset, and with \"=>\"\n" + "if a sentence frame is acceptable for the search string only."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nVerb frames of " + p.getLabel() + " " + iw.getLemma()); for (int i = 0; i < iw.getSenses().size(); i++) { Synset synset = iw.getSenses().get(i); for (String vf : synset.getVerbFrames()) { System.out.println("\t*> " + vf); } for (Word word : synset.getWords()) { if (iw.getLemma().equalsIgnoreCase(word.getLemma())) { if (word instanceof Verb) { Verb verb = (Verb) word; for (String vf : verb.getVerbFrames()) { System.out.println("\t=> " + vf); } } } } } } } //fram if (arg.startsWith("-hmer") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display meronyms for search string tree. This is a recursive search\n" + "the prints all the meronyms of the search string and all of its\n" + "hypernyms. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_MERONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hmer if (arg.startsWith("-hhol") && 6 == arg.length()) { if (needHelp) { System.out.println( "\"Display holonyms for search string tree. This is a recursive search\n" + "that prints all the holonyms of the search string and all of the\n" + "holonym's holonyms.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_HOLONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_HOLONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hhol if (arg.startsWith("-mero") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //mero if (arg.startsWith("-grep") && 6 == arg.length()) { if (needHelp) { System.out .println("Print all strings in the database containing the search string\n" + "as an individual word, or as the first or last string in a word or\n" + "collocation."); } POS p = POS.getPOSForKey(arg.substring(5)); System.out.println("\nGrep of " + p.getLabel() + " " + key); Iterator<IndexWord> ii = d.getIndexWordIterator(p, key); while (ii.hasNext()) { System.out.println(ii.next().getLemma()); } } //grep if ("-over".equals(arg)) { for (POS pos : POS.getAllPOS()) { if (null != d.getMorphologicalProcessor()) { IndexWord iw = d.getIndexWord(pos, key); //for plurals like species, glasses if (null != iw && key.equals(iw.getLemma())) { printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key); if (null != forms) { for (String form : forms) { if (!form.equals(key)) { iw = d.getIndexWord(pos, form); if (null != iw) { printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } } } } } } //over } } } } }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
public static void main(String[] args) throws IOException, ClassNotFoundException { main_completed = false;//from w w w .j av a2 s . com Options options = new Options(); options.addOption(Option.builder("?").desc("Print this message").longOpt("help").build()); options.addOption(Option.builder("n").hasArg().desc("C++ namespace for newly generated classes.") .longOpt("namespace").build()); options.addOption( Option.builder("c").hasArgs().desc("Single Java class to extract.").longOpt("classes").build()); options.addOption( Option.builder("p").hasArgs().desc("Java Package prefix to extract").longOpt("packages").build()); options.addOption(Option.builder("o").hasArg().desc("Output C++ source file.").longOpt("output").build()); options.addOption(Option.builder("j").hasArg().desc("Input jar file").longOpt("jar").build()); options.addOption(Option.builder("h").hasArg().desc("Output C++ header file.").longOpt("header").build()); options.addOption(Option.builder("l").hasArg() .desc("Maximum limit on classes to extract from jars.[default=200]").longOpt("limit").build()); options.addOption(Option.builder("v").desc("enable verbose output").longOpt("verbose").build()); options.addOption(Option.builder().hasArg().desc("Classes per output file.[default=10]") .longOpt(CLASSESPEROUTPUT).build()); options.addOption(Option.builder().hasArgs().desc( "Comma seperated list of nativeclass=javaclass native where nativeclass will be generated as an extension/implementation of the java class.") .longOpt("natives").build()); options.addOption(Option.builder().hasArg() .desc("library name for System.loadLibrary(...) for native extension classes") .longOpt("loadlibname").build()); String output = null; String header = null; String jar = null; Set<String> classnamesToFind = null; Set<String> packageprefixes = null; String loadlibname = null; Map<String, String> nativesNameMap = null; Map<String, Class> nativesClassMap = null; int limit = DEFAULT_LIMIT; int classes_per_file = 10; List<Class> classes = new ArrayList<>(); String limitstring = Integer.toString(limit); try { // parse the command line arguments System.out.println("args = " + Arrays.toString(args)); CommandLine line = new DefaultParser().parse(options, args); loadlibname = line.getOptionValue("loadlibname"); verbose = line.hasOption("verbose"); if (line.hasOption(CLASSESPEROUTPUT)) { String cpoStr = line.getOptionValue(CLASSESPEROUTPUT); try { int cpoI = Integer.valueOf(cpoStr); classes_per_file = cpoI; } catch (Exception e) { System.err.println("Option for " + CLASSESPEROUTPUT + "=\"" + cpoStr + "\""); printHelpAndExit(options, args); } } if (line.hasOption("natives")) { String natives[] = line.getOptionValues("natives"); if (verbose) { System.out.println("natives = " + Arrays.toString(natives)); } nativesNameMap = new HashMap<>(); nativesClassMap = new HashMap<>(); for (int i = 0; i < natives.length; i++) { int eq_index = natives[i].indexOf('='); String nativeClassName = natives[i].substring(0, eq_index).trim(); String javaClassName = natives[i].substring(eq_index + 1).trim(); Class javaClass = null; try { javaClass = Class.forName(javaClassName); } catch (ClassNotFoundException e) { //e.printStackTrace(); System.err.println("Class for " + javaClassName + " not found. (It may be found later in jar if specified.)"); } nativesNameMap.put(javaClassName, nativeClassName); if (javaClass != null) { nativesClassMap.put(nativeClassName, javaClass); if (!classes.contains(javaClass)) { classes.add(javaClass); } } } } // // validate that block-size has been set // if (line.hasOption("block-size")) { // // print the value of block-size // if(verbose) System.out.println(line.getOptionValue("block-size")); // } jar = line.getOptionValue("jar", jar); if (verbose) { System.out.println("jar = " + jar); } if (null != jar) { if (jar.startsWith("~/")) { jar = new File(new File(getHomeDir()), jar.substring(2)).getCanonicalPath(); } if (jar.startsWith("./")) { jar = new File(new File(getCurrentDir()), jar.substring(2)).getCanonicalPath(); } if (jar.startsWith("../")) { jar = new File(new File(getCurrentDir()).getParentFile(), jar.substring(3)).getCanonicalPath(); } } if (line.hasOption("classes")) { classnamesToFind = new HashSet<String>(); String classStrings[] = line.getOptionValues("classes"); if (verbose) { System.out.println("classStrings = " + Arrays.toString(classStrings)); } classnamesToFind.addAll(Arrays.asList(classStrings)); if (verbose) { System.out.println("classnamesToFind = " + classnamesToFind); } } // if (!line.hasOption("namespace")) { // if (classname != null && classname.length() > 0) { // namespace = classname.toLowerCase().replace(".", "_"); // } else if (jar != null && jar.length() > 0) { // int lastSep = jar.lastIndexOf(File.separator); // int start = Math.max(0, lastSep + 1); // int period = jar.indexOf('.', start + 1); // int end = Math.max(start + 1, period); // namespace = jar.substring(start, end).toLowerCase(); // namespace = namespace.replace(" ", "_"); // if (namespace.indexOf("-") > 0) { // namespace = namespace.substring(0, namespace.indexOf("-")); // } // } // } namespace = line.getOptionValue("namespace", namespace); if (verbose) { System.out.println("namespace = " + namespace); } if (null != namespace) { output = namespace + ".cpp"; } output = line.getOptionValue("output", output); if (verbose) { System.out.println("output = " + output); } if (null != output) { if (output.startsWith("~/")) { output = System.getProperty("user.home") + output.substring(1); } header = output.substring(0, output.lastIndexOf('.')) + ".h"; } else { output = "out.cpp"; } header = line.getOptionValue("header", header); if (verbose) { System.out.println("header = " + header); } if (null != header) { if (header.startsWith("~/")) { header = System.getProperty("user.home") + header.substring(1); } } else { header = "out.h"; } if (line.hasOption("packages")) { packageprefixes = new HashSet<String>(); packageprefixes.addAll(Arrays.asList(line.getOptionValues("packages"))); } if (line.hasOption("limit")) { limitstring = line.getOptionValue("limit", Integer.toString(DEFAULT_LIMIT)); limit = Integer.valueOf(limitstring); } if (line.hasOption("help")) { printHelpAndExit(options, args); } } catch (ParseException exp) { if (verbose) { System.out.println("Unexpected exception:" + exp.getMessage()); } printHelpAndExit(options, args); } Set<Class> excludedClasses = new HashSet<>(); Set<String> foundClassNames = new HashSet<>(); excludedClasses.add(Object.class); excludedClasses.add(String.class); excludedClasses.add(void.class); excludedClasses.add(Void.class); excludedClasses.add(Class.class); excludedClasses.add(Enum.class); Set<String> packagesSet = new TreeSet<>(); List<URL> urlsList = new ArrayList<>(); String cp = System.getProperty("java.class.path"); if (verbose) { System.out.println("System.getProperty(\"java.class.path\") = " + cp); } if (null != cp) { for (String cpe : cp.split(File.pathSeparator)) { if (verbose) { System.out.println("class path element = " + cpe); } File f = new File(cpe); if (f.isDirectory()) { urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator)); } else if (cpe.endsWith(".jar")) { urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/")); } } } cp = System.getenv("CLASSPATH"); if (verbose) { System.out.println("System.getenv(\"CLASSPATH\") = " + cp); } if (null != cp) { for (String cpe : cp.split(File.pathSeparator)) { if (verbose) { System.out.println("class path element = " + cpe); } File f = new File(cpe); if (f.isDirectory()) { urlsList.add(new URL("file:" + f.getCanonicalPath() + File.separator)); } else if (cpe.endsWith(".jar")) { urlsList.add(new URL("jar:file:" + f.getCanonicalPath() + "!/")); } } } if (verbose) { System.out.println("urlsList = " + urlsList); } if (null != jar && jar.length() > 0) { Path jarPath = FileSystems.getDefault().getPath(jar); ZipInputStream zip = new ZipInputStream(Files.newInputStream(jarPath, StandardOpenOption.READ)); URL jarUrl = new URL("jar:file:" + jarPath.toFile().getCanonicalPath() + "!/"); urlsList.add(jarUrl); URL[] urls = urlsList.toArray(new URL[urlsList.size()]); if (verbose) { System.out.println("urls = " + Arrays.toString(urls)); } URLClassLoader cl = URLClassLoader.newInstance(urls); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { // This ZipEntry represents a class. Now, what class does it represent? String entryName = entry.getName(); if (verbose) { System.out.println("entryName = " + entryName); } if (!entry.isDirectory() && entryName.endsWith(".class")) { if (entryName.indexOf('$') >= 0) { continue; } String classFileName = entry.getName().replace('/', '.'); String className = classFileName.substring(0, classFileName.length() - ".class".length()); if (classnamesToFind != null && classnamesToFind.size() > 0 && !classnamesToFind.contains(className)) { if (verbose) { System.out.println("skipping className=" + className + " because it does not found in=" + classnamesToFind); } continue; } try { Class clss = cl.loadClass(className); if (null != nativesClassMap && null != nativesNameMap && nativesNameMap.containsKey(className)) { nativesClassMap.put(nativesNameMap.get(className), clss); if (!classes.contains(clss)) { classes.add(clss); } } if (packageprefixes != null && packageprefixes.size() > 0) { if (null == clss.getPackage()) { continue; } final String pkgName = clss.getPackage().getName(); boolean matchFound = false; for (String prefix : packageprefixes) { if (pkgName.startsWith(prefix)) { matchFound = true; break; } } if (!matchFound) { continue; } } Package p = clss.getPackage(); if (null != p) { packagesSet.add(clss.getPackage().getName()); } if (!classes.contains(clss) && isAddableClass(clss, excludedClasses)) { if (null != classnamesToFind && classnamesToFind.contains(className) && !foundClassNames.contains(className)) { foundClassNames.add(className); if (verbose) { System.out.println("foundClassNames = " + foundClassNames); } } // if(verbose) System.out.println("clss = " + clss); classes.add(clss); // Class superClass = clss.getSuperclass(); // while (null != superClass // && !classes.contains(superClass) // && isAddableClass(superClass, excludedClasses)) { // classes.add(superClass); // superClass = superClass.getSuperclass(); // } } } catch (ClassNotFoundException | NoClassDefFoundError ex) { System.err.println( "Caught " + ex.getClass().getName() + ":" + ex.getMessage() + " for className=" + className + ", entryName=" + entryName + ", jarPath=" + jarPath); } } } } if (null != classnamesToFind) { if (verbose) { System.out.println("Checking classnames arguments"); } for (String classname : classnamesToFind) { if (verbose) { System.out.println("classname = " + classname); } if (foundClassNames.contains(classname)) { if (verbose) { System.out.println("foundClassNames.contains(" + classname + ")"); } continue; } try { if (classes.contains(Class.forName(classname))) { if (verbose) { System.out.println("Classes list already contains: " + classname); } continue; } } catch (Exception e) { } if (null != classname && classname.length() > 0) { urlsList.add(new URL("file://" + System.getProperty("user.dir") + "/")); URL[] urls = urlsList.toArray(new URL[urlsList.size()]); if (verbose) { System.out.println("urls = " + Arrays.toString(urls)); } URLClassLoader cl = URLClassLoader.newInstance(urls); Class c = null; try { c = cl.loadClass(classname); } catch (ClassNotFoundException e) { System.err.println("Class " + classname + " not found "); } if (verbose) { System.out.println("c = " + c); } if (null == c) { try { c = ClassLoader.getSystemClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { if (verbose) { System.out.println("System ClassLoader failed to find " + classname); } } } if (null != c) { classes.add(c); } else { System.err.println("Class " + classname + " not found"); } } } if (verbose) { System.out.println("Finished checking classnames arguments"); } } if (classes == null || classes.size() < 1) { if (null == nativesClassMap || nativesClassMap.keySet().size() < 1) { System.err.println("No Classes specified or found."); System.exit(1); } } if (verbose) { System.out.println("Classes found = " + classes.size()); } if (classes.size() > limit) { System.err.println("limit=" + limit); System.err.println( "Too many classes please use -c or -p options to limit classes or -l to increase limit."); if (verbose) { System.out.println("packagesSet = " + packagesSet); } System.exit(1); } List<Class> newClasses = new ArrayList<Class>(); for (Class clss : classes) { Class superClass = clss.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && isAddableClass(superClass, excludedClasses)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } try { Field fa[] = clss.getDeclaredFields(); for (Field f : fa) { if (Modifier.isPublic(f.getModifiers())) { Class fClass = f.getType(); if (!classes.contains(fClass) && !newClasses.contains(fClass) && isAddableClass(fClass, excludedClasses)) { newClasses.add(fClass); } } } } catch (NoClassDefFoundError e) { e.printStackTrace(); } for (Method m : clss.getDeclaredMethods()) { if (m.isSynthetic()) { continue; } if (!Modifier.isPublic(m.getModifiers()) || Modifier.isAbstract(m.getModifiers())) { continue; } Class retType = m.getReturnType(); if (verbose) { System.out.println("Checking dependancies for Method = " + m); } if (!classes.contains(retType) && !newClasses.contains(retType) && isAddableClass(retType, excludedClasses)) { newClasses.add(retType); superClass = retType.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && isAddableClass(superClass, excludedClasses)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } for (Class paramType : m.getParameterTypes()) { if (!classes.contains(paramType) && !newClasses.contains(paramType) && isAddableClass(paramType, excludedClasses)) { newClasses.add(paramType); superClass = paramType.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } } } } if (null != nativesClassMap) { for (Class clss : nativesClassMap.values()) { if (null != clss) { Class superClass = clss.getSuperclass(); while (null != superClass && !classes.contains(superClass) && !newClasses.contains(superClass) && !excludedClasses.contains(superClass)) { newClasses.add(superClass); superClass = superClass.getSuperclass(); } } } } if (verbose) { System.out.println("Dependency classes needed = " + newClasses.size()); } classes.addAll(newClasses); List<Class> newOrderClasses = new ArrayList<>(); for (Class clss : classes) { if (newOrderClasses.contains(clss)) { continue; } Class superClass = clss.getSuperclass(); Stack<Class> stack = new Stack<>(); while (null != superClass && !newOrderClasses.contains(superClass) && !superClass.equals(java.lang.Object.class)) { stack.push(superClass); superClass = superClass.getSuperclass(); } while (!stack.empty()) { newOrderClasses.add(stack.pop()); } newOrderClasses.add(clss); } classes = newOrderClasses; if (verbose) { System.out.println("Total number of classes = " + classes.size()); System.out.println("classes = " + classes); } String forward_header = header.substring(0, header.lastIndexOf('.')) + "_fwd.h"; Map<String, String> map = new HashMap<>(); map.put(JAR, jar != null ? jar : ""); map.put("%CLASSPATH_PREFIX%", getCurrentDir() + ((jar != null) ? (File.pathSeparator + ((new File(jar).getCanonicalPath()).replace("\\", "\\\\"))) : "")); map.put("%FORWARD_HEADER%", forward_header); map.put("%HEADER%", header); map.put("%PATH_SEPERATOR%", File.pathSeparator); String tabs = ""; String headerDefine = forward_header.substring(Math.max(0, forward_header.indexOf(File.separator))) .replace(".", "_"); map.put(HEADER_DEFINE, headerDefine); map.put(NAMESPACE, namespace); if (null != nativesClassMap) { for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassName + ".java"))) { if (javaClass.isInterface()) { pw.println("public class " + nativeClassName + " implements " + javaClass.getCanonicalName() + ", AutoCloseable{"); } else { pw.println("public class " + nativeClassName + " extends " + javaClass.getCanonicalName() + " implements AutoCloseable{"); } if (null != loadlibname && loadlibname.length() > 0) { pw.println(TAB_STRING + "static {"); pw.println(TAB_STRING + TAB_STRING + "System.loadLibrary(\"" + loadlibname + "\");"); pw.println(TAB_STRING + "}"); pw.println(); } pw.println(TAB_STRING + "public " + nativeClassName + "() {"); pw.println(TAB_STRING + "}"); pw.println(); pw.println(TAB_STRING + "private long nativeAddress=0;"); pw.println(TAB_STRING + "private boolean nativeDeleteOnClose=false;"); pw.println(); pw.println(TAB_STRING + "protected " + nativeClassName + "(final long nativeAddress) {"); pw.println(TAB_STRING + TAB_STRING + "this.nativeAddress = nativeAddress;"); pw.println(TAB_STRING + "}"); pw.println(TAB_STRING + "private native void nativeDelete();"); pw.println(); pw.println(TAB_STRING + "@Override"); pw.println(TAB_STRING + "public synchronized void close() {"); // pw.println(TAB_STRING + TAB_STRING + "if(nativeAddress != 0 && nativeDeleteOnClose) {"); pw.println(TAB_STRING + TAB_STRING + "nativeDelete();"); // pw.println(TAB_STRING + TAB_STRING + "}"); // pw.println(TAB_STRING + TAB_STRING + "nativeAddress=0;"); // pw.println(TAB_STRING + TAB_STRING + "nativeDeleteOnClose=false;"); pw.println(TAB_STRING + "}"); pw.println(); pw.println(TAB_STRING + "protected void finalizer() {"); pw.println(TAB_STRING + TAB_STRING + "close();"); pw.println(TAB_STRING + "}"); pw.println(); Method ma[] = javaClass.getDeclaredMethods(); for (Method m : ma) { int modifiers = m.getModifiers(); if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !m.isDefault() && !m.isSynthetic()) { pw.println(); pw.println(TAB_STRING + "@Override"); String params = ""; for (int i = 0; i < m.getParameterTypes().length; i++) { params += m.getParameterTypes()[i].getCanonicalName() + " param" + i; if (i < m.getParameterTypes().length - 1) { params += ","; } } pw.println(TAB_STRING + "native public " + m.getReturnType().getCanonicalName() + " " + m.getName() + "(" + params + ");"); // + IntStream.range(0, m.getParameterTypes().length) // .mapToObj(i -> m.getParameterTypes()[i].getCanonicalName() + " param" + i) // .collect(Collectors.joining(",")) + ");"); } } pw.println("}"); } } } try (PrintWriter pw = new PrintWriter(new FileWriter(forward_header))) { tabs = ""; processTemplate(pw, map, "header_fwd_template_start.h", tabs); Class lastClass = null; for (int class_index = 0; class_index < classes.size(); class_index++) { Class clss = classes.get(class_index); String clssOnlyName = getCppClassName(clss); tabs = openClassNamespace(clss, pw, tabs, lastClass); tabs += TAB_STRING; pw.println(tabs + "class " + clssOnlyName + ";"); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classes.size() - 1)) ? classes.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); lastClass = clss; } processTemplate(pw, map, "header_fwd_template_end.h", tabs); } headerDefine = header.substring(Math.max(0, header.indexOf(File.separator))).replace(".", "_"); map.put(HEADER_DEFINE, headerDefine); map.put(NAMESPACE, namespace); if (classes_per_file < 1) { classes_per_file = classes.size(); } final int num_class_segments = (classes.size() > 1) ? ((classes.size() + classes_per_file - 1) / classes_per_file) : 1; String fmt = "%d"; if (num_class_segments > 10) { fmt = "%02d"; } if (num_class_segments > 100) { fmt = "%03d"; } String header_file_base = header; if (header_file_base.endsWith(".h")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 2); } else if (header_file_base.endsWith(".hh")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 3); } else if (header_file_base.endsWith(".hpp")) { header_file_base = header_file_base.substring(0, header_file_base.length() - 4); } try (PrintWriter pw = new PrintWriter(new FileWriter(header))) { tabs = ""; processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs); for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h"; pw.println("#include \"" + header_segment_file + "\""); } if (null != nativesClassMap) { tabs = TAB_STRING; for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); pw.println(); pw.println(tabs + "class " + nativeClassName + "Context;"); pw.println(); map.put(CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); processTemplate(pw, map, HEADER_CLASS_STARTH, tabs); tabs += TAB_STRING; pw.println(tabs + nativeClassName + "Context *context;"); pw.println(tabs + nativeClassName + "();"); pw.println(tabs + "~" + nativeClassName + "();"); Method methods[] = javaClass.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { pw.println(tabs + getNativeMethodCppDeclaration(method, javaClass)); } } pw.println(tabs + "void initContext(" + nativeClassName + "Context *ctx,bool isref);"); pw.println(tabs + "void deleteContext();"); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}; // end class " + nativeClassName); } } tabs = ""; processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs); } for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String header_segment_file = header_file_base + String.format(fmt, segment_index) + ".h"; try (PrintWriter pw = new PrintWriter(new FileWriter(header_segment_file))) { tabs = ""; //processTemplate(pw, map, HEADER_TEMPLATE_STARTH, tabs); pw.println("// Never include this file (" + header_segment_file + ") directly. include " + header + " instead."); pw.println(); Class lastClass = null; final int start_segment_index = segment_index * classes_per_file; final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file, classes.size()); List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index); pw.println(); pw.println(tabs + "// start_segment_index = " + start_segment_index); pw.println(tabs + "// start_segment_index = " + end_segment_index); pw.println(tabs + "// segment_index = " + segment_index); pw.println(tabs + "// classesSegList=" + classesSegList); pw.println(); for (int class_index = 0; class_index < classesSegList.size(); class_index++) { Class clss = classesSegList.get(class_index); pw.println(); pw.println(tabs + "// class_index = " + class_index + " clss=" + clss); pw.println(); String clssName = clss.getCanonicalName(); tabs = openClassNamespace(clss, pw, tabs, lastClass); String clssOnlyName = getCppClassName(clss); map.put(CLASS_NAME, clssOnlyName); map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss)); map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss)); tabs += TAB_STRING; processTemplate(pw, map, HEADER_CLASS_STARTH, tabs); tabs += TAB_STRING; Constructor constructors[] = clss.getDeclaredConstructors(); if (!hasNoArgConstructor(constructors)) { if (Modifier.isAbstract(clss.getModifiers()) || clss.isInterface()) { pw.println(tabs + "protected:"); pw.println(tabs + clssOnlyName + "() {};"); pw.println(tabs + "public:"); } else { if (constructors.length > 0) { pw.println(tabs + "protected:"); } pw.println(tabs + clssOnlyName + "();"); if (constructors.length > 0) { pw.println(tabs + "public:"); } } } for (Constructor c : constructors) { if (c.getParameterTypes().length == 0 && Modifier.isProtected(c.getModifiers())) { pw.println(tabs + "protected:"); pw.println(tabs + clssOnlyName + "();"); pw.println(tabs + "public:"); } if (checkConstructor(c, clss, classes)) { continue; } if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) { continue; } if (!Modifier.isPublic(c.getModifiers())) { continue; } if (c.getParameterTypes().length == 1) { if (c.getParameterTypes()[0].getName().equals(clss.getName())) { // if(verbose) System.out.println("skipping constructor."); continue; } } if (!checkParameters(c.getParameterTypes(), classes)) { continue; } pw.println( tabs + clssOnlyName + getCppParamDeclarations(c.getParameterTypes(), clss) + ";"); if (isConstructorToMakeEasy(c, clss)) { pw.println(tabs + clssOnlyName + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + ";"); } } pw.println(tabs + "~" + clssOnlyName + "();"); Field fa[] = clss.getDeclaredFields(); for (int findex = 0; findex < fa.length; findex++) { Field field = fa[findex]; if (addGetterMethod(field, clss, classes)) { pw.println(tabs + getCppFieldGetterDeclaration(field, clss)); } if (addSetterMethod(field, clss, classes)) { pw.println(tabs + getCppFieldSetterDeclaration(field, clss)); } } Method methods[] = clss.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; if (!checkMethod(method, classes)) { continue; } if ((method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) { pw.println(tabs + getCppDeclaration(method, clss)); } if (isArrayStringMethod(method)) { pw.println(tabs + getCppModifiers(method.getModifiers()) + getCppType(method.getReturnType(), clss) + " " + fixMethodName(method) + "(int argc,const char **argv);"); } if (isMethodToMakeEasy(method)) { pw.println(tabs + getEasyCallCppDeclaration(method, clss)); } } tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}; // end class " + clssOnlyName); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classesSegList.size() - 1)) ? classesSegList.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); pw.println(); lastClass = clss; } //processTemplate(pw, map, HEADER_TEMPLATE_ENDH, tabs); } } for (int segment_index = 0; segment_index < num_class_segments; segment_index++) { String output_segment_file = output; if (output_segment_file.endsWith(".cpp")) { output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 4); } else if (output_segment_file.endsWith(".cc")) { output_segment_file = output_segment_file.substring(0, output_segment_file.length() - 3); } output_segment_file += "" + String.format(fmt, segment_index) + ".cpp"; try (PrintWriter pw = new PrintWriter(new FileWriter(output_segment_file))) { tabs = ""; if (segment_index < 1) { processTemplate(pw, map, "cpp_template_start_first.cpp", tabs); } else { processTemplate(pw, map, CPP_TEMPLATE_STARTCPP, tabs); } final int start_segment_index = segment_index * classes_per_file; final int end_segment_index = Math.min(segment_index * classes_per_file + classes_per_file, classes.size()); List<Class> classesSegList = classes.subList(start_segment_index, end_segment_index); pw.println(); pw.println(tabs + "// start_segment_index = " + start_segment_index); pw.println(tabs + "// start_segment_index = " + end_segment_index); pw.println(tabs + "// segment_index = " + segment_index); pw.println(tabs + "// classesSegList=" + classesSegList); pw.println(); Class lastClass = null; for (int class_index = 0; class_index < classesSegList.size(); class_index++) { Class clss = classesSegList.get(class_index); pw.println(); pw.println(tabs + "// class_index = " + class_index + " clss=" + clss); pw.println(); String clssName = clss.getCanonicalName(); tabs = openClassNamespace(clss, pw, tabs, lastClass); String clssOnlyName = getCppClassName(clss); map.put(CLASS_NAME, clssOnlyName); map.put("%BASE_CLASS_FULL_NAME%", classToCppBase(clss)); map.put(FULL_CLASS_NAME, clssName); String fcjs = classToJNISignature(clss); fcjs = fcjs.substring(1, fcjs.length() - 1); map.put(FULL_CLASS_JNI_SIGNATURE, fcjs); if (verbose) { System.out.println("fcjs = " + fcjs); } map.put(OBJECT_CLASS_FULL_NAME, getCppRelativeName(Object.class, clss)); map.put("%INITIALIZE_CONTEXT%", ""); map.put("%INITIALIZE_CONTEXT_REF%", ""); processTemplate(pw, map, CPP_START_CLASSCPP, tabs); Constructor constructors[] = clss.getDeclaredConstructors(); if (!hasNoArgConstructor(constructors)) { if (!Modifier.isAbstract(clss.getModifiers()) && !clss.isInterface()) { pw.println(tabs + clssOnlyName + "::" + clssOnlyName + "() : " + classToCppBase(clss) + "((jobject)NULL,false) {"); map.put(JNI_SIGNATURE, "()V"); map.put(CONSTRUCTOR_ARGS, ""); processTemplate(pw, map, CPP_NEWCPP, tabs); pw.println(tabs + "}"); pw.println(); } } for (Constructor c : constructors) { if (checkConstructor(c, clss, classes)) { continue; } Class[] paramClasses = c.getParameterTypes(); pw.println(tabs + clssOnlyName + "::" + clssOnlyName + getCppParamDeclarations(paramClasses, clss) + " : " + classToCppBase(clss) + "((jobject)NULL,false) {"); tabs = tabs + TAB_STRING; map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")V"); map.put(CONSTRUCTOR_ARGS, (paramClasses.length > 0 ? "," : "") + getCppParamNames(paramClasses)); processTemplate(pw, map, CPP_NEWCPP, tabs); tabs = tabs.substring(0, tabs.length() - 1); pw.println(tabs + "}"); pw.println(); if (isConstructorToMakeEasy(c, clss)) { pw.println(tabs + clssOnlyName + "::" + clssOnlyName + getEasyCallCppParamDeclarations(c.getParameterTypes(), clss) + " : " + classToCppBase(clss) + "((jobject)NULL,false) {"); processTemplate(pw, map, "cpp_start_easy_constructor.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_" + paramIndex + ");"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= env->New" + callString + "Array(easyArg_" + paramIndex + "_length);"); pw.println(tabs + "env->Set" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); } else { pw.println(tabs + getCppType(paramClasse, clss) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_" + paramIndex + ";"); } } processTemplate(pw, map, "cpp_new_easy_internals.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + "env->Get" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else { } } processTemplate(pw, map, "cpp_end_easy_constructor.cpp", tabs); pw.println(tabs + "}"); } } pw.println(); pw.println(tabs + "// Destructor for " + clssName); pw.println(tabs + clssOnlyName + "::~" + clssOnlyName + "() {"); pw.println(tabs + "\t// Place-holder for later extensibility."); pw.println(tabs + "}"); pw.println(); Field fa[] = clss.getDeclaredFields(); for (int findex = 0; findex < fa.length; findex++) { Field field = fa[findex]; if (addGetterMethod(field, clss, classes)) { pw.println(); pw.println(tabs + "// Field getter for " + field.getName()); pw.println(getCppFieldGetterDefinitionStart(tabs, clssOnlyName, field, clss)); map.put("%FIELD_NAME%", field.getName()); map.put(JNI_SIGNATURE, classToJNISignature(field.getType())); Class returnClass = field.getType(); map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); map.put(METHOD_ARGS, ""); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass)); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); if (Modifier.isStatic(field.getModifiers())) { processTemplate(pw, map, "cpp_static_getfield.cpp", tabs); } else { processTemplate(pw, map, "cpp_getfield.cpp", tabs); } pw.println(tabs + "}"); } if (addSetterMethod(field, clss, classes)) { pw.println(); pw.println(tabs + "// Field setter for " + field.getName()); pw.println(getCppFieldSetterDefinitionStart(tabs, clssOnlyName, field, clss)); map.put("%FIELD_NAME%", field.getName()); map.put(JNI_SIGNATURE, classToJNISignature(field.getType())); Class returnClass = void.class; map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); Class[] paramClasses = new Class[] { field.getType() }; String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(field.getType())); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); if (Modifier.isStatic(field.getModifiers())) { processTemplate(pw, map, "cpp_static_setfield.cpp", tabs); } else { processTemplate(pw, map, "cpp_setfield.cpp", tabs); } pw.println(tabs + "}"); } } Method methods[] = clss.getDeclaredMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; if (checkMethod(method, classes)) { pw.println(); pw.println(getCppMethodDefinitionStart(tabs, clssOnlyName, method, clss)); map.put(METHOD_NAME, method.getName()); if (fixMethodName(method).contains("equals2")) { if (verbose) { System.out.println("debug me"); } } map.put("%JAVA_METHOD_NAME%", method.getName()); Class[] paramClasses = method.getParameterTypes(); String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, (paramClasses.length > 0 ? "," : "") + methodArgs); Class returnClass = method.getReturnType(); map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(paramClasses) + ")" + classToJNISignature(returnClass)); map.put(METHOD_ONFAIL, getOnFailString(returnClass, clss)); map.put("%METHOD_RETURN%", isVoid(returnClass) ? "" : "return"); map.put("%METHOD_CALL_TYPE%", getMethodCallString(returnClass)); map.put("%METHOD_RETURN_TYPE%", getCppType(returnClass, clss)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, clss)); tabs += TAB_STRING; if (!Modifier.isStatic(method.getModifiers())) { processTemplate(pw, map, CPP_METHODCPP, tabs); } else { processTemplate(pw, map, CPP_STATIC_METHODCPP, tabs); } tabs = tabs.substring(0, tabs.length() - TAB_STRING.length()); pw.println(tabs + "}"); if (isArrayStringMethod(method)) { map.put(METHOD_RETURN_STORE, isVoid(returnClass) ? "" : getCppType(returnClass, clss) + " returnVal="); map.put(METHOD_RETURN_GET, isVoid(returnClass) ? "return ;" : "return returnVal;"); processTemplate(pw, map, CPP_EASY_STRING_ARRAY_METHODCPP, tabs); } else if (isMethodToMakeEasy(method)) { pw.println(); pw.println(tabs + "// Easy call alternative for " + method.getName()); pw.println(getEasyCallCppMethodDefinitionStart(tabs, clssOnlyName, method, clss)); tabs += TAB_STRING; map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclareOut(returnClass, clss)); processTemplate(pw, map, "cpp_start_easy_method.cpp", tabs); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jstring " + parmName + " = env->NewStringUTF(easyArg_" + paramIndex + ");"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + getCppArrayType(paramClasse.getComponentType()) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= env->New" + callString + "Array(easyArg_" + paramIndex + "_length);"); pw.println(tabs + "env->Set" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); } else { pw.println(tabs + getCppType(paramClasse, clss) + " " + classToParamNameDecl(paramClasse, paramIndex) + "= easyArg_" + paramIndex + ";"); } } String methodArgsIn = getCppParamNamesIn(paramClasses); String retStoreOut = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnOutVarType(returnClass, clss) + ") "; pw.println(tabs + retStoreOut + fixMethodName(method) + "(" + methodArgsIn + ");"); for (int paramIndex = 0; paramIndex < paramClasses.length; paramIndex++) { Class paramClasse = paramClasses[paramIndex]; String parmName = getParamNameIn(paramClasse, paramIndex); if (isString(paramClasse)) { pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else if (isPrimitiveArray(paramClasse)) { String callString = getMethodCallString(paramClasse.getComponentType()); pw.println(tabs + "env->Get" + callString + "ArrayRegion(" + classToParamNameDecl(paramClasse, paramIndex) + ",0,easyArg_" + paramIndex + "_length,easyArg_" + paramIndex + ");"); pw.println(tabs + "jobjectRefType ref_" + paramIndex + " = env->GetObjectRefType(" + parmName + ");"); pw.println(tabs + "if(ref_" + paramIndex + " == JNIGlobalRefType) {"); pw.println(tabs + TAB_STRING + "env->DeleteGlobalRef(" + parmName + ");"); pw.println(tabs + "}"); } else { } } processTemplate(pw, map, "cpp_end_easy_method.cpp", tabs); if (!isVoid(returnClass)) { pw.println(tabs + "return retVal;"); } tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); } } } processTemplate(pw, map, CPP_END_CLASSCPP, tabs); tabs = tabs.substring(0, tabs.length() - 1); Class nextClass = (class_index < (classesSegList.size() - 1)) ? classesSegList.get(class_index + 1) : null; tabs = closeClassNamespace(clss, pw, tabs, nextClass); lastClass = clss; } if (segment_index < 1) { if (null != nativesClassMap) { for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); map.put("%INITIALIZE_CONTEXT%", "context=NULL; initContext(NULL,false);"); map.put("%INITIALIZE_CONTEXT_REF%", "context=NULL; initContext(objref.context,true);"); tabs += TAB_STRING; processTemplate(pw, map, CPP_START_CLASSCPP, tabs); pw.println(); pw.println(tabs + nativeClassName + "::" + nativeClassName + "() : " + getModifiedClassName(javaClass).replace(".", "::") + "((jobject)NULL,false) {"); tabs += TAB_STRING; pw.println(tabs + "context=NULL;"); pw.println(tabs + "initContext(NULL,false);"); map.put(JNI_SIGNATURE, "()V"); map.put(CONSTRUCTOR_ARGS, ""); processTemplate(pw, map, "cpp_new_native.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); pw.println(tabs + "// Destructor for " + nativeClassName); pw.println(tabs + nativeClassName + "::~" + nativeClassName + "() {"); pw.println(tabs + TAB_STRING + "if(NULL != context) {"); pw.println(tabs + TAB_STRING + TAB_STRING + "deleteContext();"); pw.println(tabs + TAB_STRING + "}"); pw.println(tabs + TAB_STRING + "context=NULL;"); pw.println(tabs + "}"); pw.println(); // pw.println(tabs + "public:"); // pw.println(tabs + nativeClassName + "();"); // pw.println(tabs + "~" + nativeClassName + "();"); tabs = tabs.substring(TAB_STRING.length()); // Method methods[] = javaClass.getDeclaredMethods(); // for (int j = 0; j < methods.length; j++) { // Method method = methods[j]; // int modifiers = method.getModifiers(); // if (!Modifier.isPublic(modifiers)) { // continue; // } // pw.println(tabs + getCppDeclaration(method, javaClass)); // } // pw.println(tabs + "}; // end class " + nativeClassName); processTemplate(pw, map, CPP_END_CLASSCPP, tabs); } } processTemplate(pw, map, "cpp_template_end_first.cpp", tabs); tabs = ""; if (null != nativesClassMap) { pw.println("using namespace " + namespace + ";"); pw.println("#ifdef __cplusplus"); pw.println("extern \"C\" {"); pw.println("#endif"); int max_method_count = 0; tabs = ""; for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); map.put(FULL_CLASS_JNI_SIGNATURE, nativeClassName); map.put(METHOD_ONFAIL, "return;"); Method methods[] = javaClass.getDeclaredMethods(); if (max_method_count < methods.length) { max_method_count = methods.length; } for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { Class[] paramClasses = method.getParameterTypes(); String methodArgs = getCppParamNames(paramClasses); map.put(METHOD_ARGS, methodArgs); map.put(METHOD_NAME, method.getName()); Class returnClass = method.getReturnType(); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, javaClass)); pw.println(); String paramDecls = getCppParamDeclarations(paramClasses, javaClass); String argsToAdd = method.getParameterTypes().length > 0 ? "," + paramDecls.substring(1, paramDecls.length() - 1) : ""; pw.println("JNIEXPORT " + getCppType(returnClass, javaClass) + " JNICALL Java_" + nativeClassName + "_" + method.getName() + "(JNIEnv *env, jobject jthis" + argsToAdd + ") {"); tabs = TAB_STRING; processTemplate(pw, map, "cpp_native_wrap.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println("}"); pw.println(); } } pw.println("JNIEXPORT void JNICALL Java_" + nativeClassName + "_nativeDelete(JNIEnv *env, jobject jthis) {"); tabs += TAB_STRING; map.put(METHOD_ONFAIL, getOnFailString(void.class, javaClass)); processTemplate(pw, map, "cpp_native_delete.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); pw.println(tabs + "}"); pw.println(); } pw.println("#ifdef __cplusplus"); pw.println("} // end extern \"C\""); pw.println("#endif"); map.put("%MAX_METHOD_COUNT%", Integer.toString(max_method_count + 1)); processTemplate(pw, map, "cpp_start_register_native.cpp", tabs); for (Entry<String, Class> e : nativesClassMap.entrySet()) { final Class javaClass = e.getValue(); final String nativeClassName = e.getKey(); map.put(CLASS_NAME, nativeClassName); map.put(FULL_CLASS_NAME, nativeClassName); map.put("%BASE_CLASS_FULL_NAME%", "::" + namespace + "::" + getModifiedClassName(javaClass).replace(".", "::")); map.put(OBJECT_CLASS_FULL_NAME, "::" + namespace + "::java::lang::Object"); processTemplate(pw, map, "cpp_start_register_native_class.cpp", tabs); tabs += TAB_STRING; Method methods[] = javaClass.getDeclaredMethods(); int method_number = 0; for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { map.put("%METHOD_NUMBER%", Integer.toString(method_number)); map.put(METHOD_NAME, method.getName()); map.put(JNI_SIGNATURE, "(" + getJNIParamSignature(method.getParameterTypes()) + ")" + classToJNISignature(method.getReturnType())); processTemplate(pw, map, "cpp_register_native_item.cpp", tabs); method_number++; } } map.put("%METHOD_NUMBER%", Integer.toString(method_number)); map.put(METHOD_NAME, "nativeDelete"); map.put(JNI_SIGNATURE, "()V"); processTemplate(pw, map, "cpp_register_native_item.cpp", tabs); map.put("%NUM_NATIVE_METHODS%", Integer.toString(method_number)); processTemplate(pw, map, "cpp_end_register_native_class.cpp", tabs); tabs = tabs.substring(TAB_STRING.length()); } processTemplate(pw, map, "cpp_end_register_native.cpp", tabs); } else { pw.println("// No Native classes : registerNativMethods not needed."); pw.println("static void registerNativeMethods(JNIEnv *env) {}"); } } else { processTemplate(pw, map, CPP_TEMPLATE_ENDCPP, tabs); } } if (null != nativesClassMap) { tabs = ""; for (Entry<String, Class> e : nativesClassMap.entrySet()) { String nativeClassName = e.getKey(); File nativeClassHeaderFile = new File( namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".h"); map.put("%NATIVE_CLASS_HEADER%", nativeClassHeaderFile.getName()); map.put(CLASS_NAME, nativeClassName); if (nativeClassHeaderFile.exists()) { if (verbose) { System.out.println("skipping " + nativeClassHeaderFile.getCanonicalPath() + " since it already exists."); } } else { try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassHeaderFile))) { processTemplate(pw, map, "header_native_imp.h", tabs); } } File nativeClassCppFile = new File( namespace.toLowerCase() + "_" + nativeClassName.toLowerCase() + ".cpp"); if (nativeClassCppFile.exists()) { if (verbose) { System.out.println("skipping " + nativeClassCppFile.getCanonicalPath() + " since it already exists."); } } else { try (PrintWriter pw = new PrintWriter(new FileWriter(nativeClassCppFile))) { processTemplate(pw, map, "cpp_native_imp_start.cpp", tabs); Class javaClass = e.getValue(); Method methods[] = javaClass.getDeclaredMethods(); int method_number = 0; for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int modifiers = method.getModifiers(); if (!Modifier.isPublic(modifiers)) { continue; } if (Modifier.isAbstract(modifiers) && Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) // && !method.isDefault() && !method.isSynthetic()) { Class[] paramClasses = method.getParameterTypes(); // String methodArgs = getCppParamNames(paramClasses); String paramDecls = getCppParamDeclarations(paramClasses, javaClass); String methodArgs = method.getParameterTypes().length > 0 ? paramDecls.substring(1, paramDecls.length() - 1) : ""; map.put(METHOD_ARGS, methodArgs); map.put(METHOD_NAME, method.getName()); Class returnClass = method.getReturnType(); String retStore = isVoid(returnClass) ? "" : "retVal= (" + getMethodReturnVarType(returnClass) + ") "; map.put(METHOD_ONFAIL, getOnFailString(returnClass, javaClass)); map.put("%RETURN_TYPE%", getCppType(returnClass, javaClass)); map.put("%RETURN_VAR_DECLARE%", getMethodReturnVarDeclare(returnClass)); map.put("%METHOD_RETURN_STORE%", retStore); map.put("%METHOD_RETURN_GET%", getMethodReturnGet(tabs, returnClass, javaClass)); processTemplate(pw, map, "cpp_native_imp_stub.cpp", tabs); } } processTemplate(pw, map, "cpp_native_imp_end.cpp", tabs); } } } } } main_completed = true; }
From source file:com.rackspacecloud.client.cloudfiles.sample.FilesCopy.java
public static void main(String args[]) throws NoSuchAlgorithmException, FilesException { //Build the command line options Options options = addCommandLineOptions(); if (args.length <= 0) printHelp(options);/*from www . j a v a 2 s. c om*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help")) printHelp(options); if (line.hasOption("file") && line.hasOption("folder")) { System.err.println("Can not use both -file and -folder on the command line at the same time."); System.exit(-1); } //if (line.hasOption("file") && line.hasOption("folder")) if (line.hasOption("download")) { if (line.hasOption("folder")) { String localFolder = FilenameUtils.normalize(line.getOptionValue("folder")); String containerName = null; if (StringUtils.isNotBlank(localFolder)) { File localFolderObj = new File(localFolder); if (localFolderObj.exists() && localFolderObj.isDirectory()) { if (line.hasOption("container")) { containerName = line.getOptionValue("container"); if (!StringUtils.isNotBlank(containerName)) { System.err.println( "You must provide a valid value for the Container to upload to !"); System.exit(-1); } //if (!StringUtils.isNotBlank(ontainerName)) } else { System.err.println( "You must provide the -container for a copy operation to work as expected."); System.exit(-1); } System.out.println("Downloading all objects from: " + containerName + " to local folder: " + localFolder); getContainerObjects(localFolderObj, containerName); } else { if (!localFolderObj.exists()) { System.err.println("The local folder: " + localFolder + " does not exist. Create it first and then run this command."); } if (!localFolderObj.isDirectory()) { System.err.println( "The local folder name supplied : " + localFolder + " is not a folder !"); } System.exit(-1); } } } System.exit(0); } //if (line.hasOption("download")) if (line.hasOption("folder")) { String containerName = null; String folderPath = null; if (line.hasOption("container")) { containerName = line.getOptionValue("container"); if (!StringUtils.isNotBlank(containerName)) { System.err.println("You must provide a valid value for the Container to upload to !"); System.exit(-1); } //if (!StringUtils.isNotBlank(containerName)) } else { System.err.println("You must provide the -container for a copy operation to work as expected."); System.exit(-1); } folderPath = line.getOptionValue("folder"); if (StringUtils.isNotBlank(folderPath)) { File folder = new File(FilenameUtils.normalize(folderPath)); if (folder.isDirectory()) { if (line.hasOption("z")) { System.out.println("Zipping: " + folderPath); System.out.println("Nested folders are ignored !"); File zipedFolder = zipFolder(folder); String mimeType = FilesConstants.getMimetype(ZIPEXTENSION); copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName); } else { File[] files = folder.listFiles(); for (File f : files) { String mimeType = FilesConstants .getMimetype(FilenameUtils.getExtension(f.getName())); System.out.println("Uploading :" + f.getName() + " to " + folder.getName()); copyToCreateContainerIfNeeded(f, mimeType, containerName); System.out.println( "Upload :" + f.getName() + " to " + folder.getName() + " completed."); } } } else { System.err.println("You must provide a valid folder value for the -folder option !"); System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath)); System.exit(-1); } } } //if (line.hasOption("folder")) if (line.hasOption("file")) { String containerName = null; String fileNamePath = null; if (line.hasOption("container")) { containerName = line.getOptionValue("container"); if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) { System.err.println("You must provide a valid value for the Container to upload to !"); System.exit(-1); } //if (!StringUtils.isNotBlank(containerName)) } else { System.err.println("You must provide the -container for a copy operation to work as expected."); System.exit(-1); } fileNamePath = line.getOptionValue("file"); if (StringUtils.isNotBlank(fileNamePath)) { String fileName = FilenameUtils.normalize(fileNamePath); String fileExt = FilenameUtils.getExtension(fileNamePath); String mimeType = FilesConstants.getMimetype(fileExt); File file = new File(fileName); if (line.hasOption("z")) { logger.info("Zipping " + fileName); if (!file.isDirectory()) { File zippedFile = zipFile(file); mimeType = FilesConstants.getMimetype(ZIPEXTENSION); copyTo(zippedFile, mimeType, containerName); zippedFile.delete(); } } //if (line.hasOption("z")) else { logger.info("Uploading " + fileName + "."); if (!file.isDirectory()) copyTo(file, mimeType, containerName); else { System.err.println( "The path you provided is a folder. For uploading folders use the -folder option."); System.exit(-1); } } } //if (StringUtils.isNotBlank(file)) else { System.err.println("You must provide a valid value for the file to upload !"); System.exit(-1); } } //if (line.hasOption("file")) } //end try catch (ParseException err) { System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); err.printStackTrace(System.err); } //catch( ParseException err ) catch (FilesAuthorizationException err) { logger.fatal("FilesAuthorizationException : Failed to login to your account !" + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); } //catch (FilesAuthorizationException err) catch (Exception err) { logger.fatal("IOException : " + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); } //catch ( IOException err) }
From source file:com.mosso.client.cloudfiles.sample.FilesCopy.java
public static void main(String args[]) throws NoSuchAlgorithmException, FilesException { //Build the command line options Options options = addCommandLineOptions(); if (args.length <= 0) printHelp(options);//from w w w .ja v a2s . c o m CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("help")) printHelp(options); if (line.hasOption("file") && line.hasOption("folder")) { System.err.println("Can not use both -file and -folder on the command line at the same time."); System.exit(-1); } //if (line.hasOption("file") && line.hasOption("folder")) if (line.hasOption("download")) { if (line.hasOption("folder")) { String localFolder = FilenameUtils.normalize(line.getOptionValue("folder")); String containerName = null; if (StringUtils.isNotBlank(localFolder)) { File localFolderObj = new File(localFolder); if (localFolderObj.exists() && localFolderObj.isDirectory()) { if (line.hasOption("container")) { containerName = line.getOptionValue("container"); if (!StringUtils.isNotBlank(containerName)) { System.err.println( "You must provide a valid value for the Container to upload to !"); System.exit(-1); } //if (!StringUtils.isNotBlank(ontainerName)) } else { System.err.println( "You must provide the -container for a copy operation to work as expected."); System.exit(-1); } System.out.println("Downloading all objects from: " + containerName + " to local folder: " + localFolder); getContainerObjects(localFolderObj, containerName); } else { if (!localFolderObj.exists()) { System.err.println("The local folder: " + localFolder + " does not exist. Create it first and then run this command."); } if (!localFolderObj.isDirectory()) { System.err.println( "The local folder name supplied : " + localFolder + " is not a folder !"); } System.exit(-1); } } } System.exit(0); } //if (line.hasOption("download")) if (line.hasOption("folder")) { String containerName = null; String folderPath = null; if (line.hasOption("container")) { containerName = line.getOptionValue("container"); if (!StringUtils.isNotBlank(containerName)) { System.err.println("You must provide a valid value for the Container to upload to !"); System.exit(-1); } //if (!StringUtils.isNotBlank(containerName)) } else { System.err.println("You must provide the -container for a copy operation to work as expected."); System.exit(-1); } folderPath = line.getOptionValue("folder"); if (StringUtils.isNotBlank(folderPath)) { File folder = new File(FilenameUtils.normalize(folderPath)); if (folder.isDirectory()) { if (line.hasOption("z")) { System.out.println("Zipping: " + folderPath); System.out.println("Nested folders are ignored !"); File zipedFolder = zipFolder(folder); String mimeType = FilesConstants.getMimetype(ZIPEXTENSION); copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName); } else { File[] files = folder.listFiles(); for (File f : files) { String mimeType = FilesConstants .getMimetype(FilenameUtils.getExtension(f.getName())); System.out.println("Uploading :" + f.getName() + " to " + folder.getName()); copyToCreateContainerIfNeeded(f, mimeType, containerName); System.out.println( "Upload :" + f.getName() + " to " + folder.getName() + " completed."); } } } else { System.err.println("You must provide a valid folder value for the -folder option !"); System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath)); System.exit(-1); } } } //if (line.hasOption("folder")) if (line.hasOption("file")) { String containerName = null; String fileNamePath = null; if (line.hasOption("container")) { containerName = line.getOptionValue("container"); if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) { System.err.println("You must provide a valid value for the Container to upload to !"); System.exit(-1); } //if (!StringUtils.isNotBlank(containerName)) } else { System.err.println("You must provide the -container for a copy operation to work as expected."); System.exit(-1); } fileNamePath = line.getOptionValue("file"); if (StringUtils.isNotBlank(fileNamePath)) { String fileName = FilenameUtils.normalize(fileNamePath); String fileExt = FilenameUtils.getExtension(fileNamePath); String mimeType = FilesConstants.getMimetype(fileExt); File file = new File(fileName); if (line.hasOption("z")) { logger.info("Zipping " + fileName); if (!file.isDirectory()) { File zippedFile = zipFile(file); mimeType = FilesConstants.getMimetype(ZIPEXTENSION); copyTo(zippedFile, mimeType, containerName); zippedFile.delete(); } } //if (line.hasOption("z")) else { logger.info("Uploading " + fileName + "."); if (!file.isDirectory()) copyTo(file, mimeType, containerName); else { System.err.println( "The path you provided is a folder. For uploading folders use the -folder option."); System.exit(-1); } } } //if (StringUtils.isNotBlank(file)) else { System.err.println("You must provide a valid value for the file to upload !"); System.exit(-1); } } //if (line.hasOption("file")) } //end try catch (ParseException err) { System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); err.printStackTrace(System.err); } //catch( ParseException err ) catch (FilesAuthorizationException err) { logger.fatal("FilesAuthorizationException : Failed to login to your account !" + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); } //catch (FilesAuthorizationException err) catch (IOException err) { logger.fatal("IOException : " + err); System.err.println("Please see the logs for more details. Error Message: " + err.getMessage()); } //catch ( IOException err) }
From source file:CTmousetrack.java
public static void main(String[] args) { String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder String srcName = "CTmousetrack"; // name of the output CT source long blockPts = 10; // points per block flush long sampInterval = 10; // time between sampling updates, msec double trimTime = 0.0; // amount of data to keep (trim time), sec boolean debug = false; // turn on debug? // Specify the CT output connection CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data String serverHost = ""; // Server (FTP or HTTP/S) host:port String serverUser = ""; // Server (FTP or HTTPS) username String serverPassword = ""; // Server (FTP or HTTPS) password // For UDP output mode DatagramSocket udpServerSocket = null; InetAddress udpServerAddress = null; String udpHost = ""; int udpPort = -1; // Concatenate all of the CTWriteMode types String possibleWriteModes = ""; for (CTWriteMode wm : CTWriteMode.values()) { possibleWriteModes = possibleWriteModes + ", " + wm.name(); }/*from w w w .j a v a 2s . c o m*/ // Remove ", " from start of string possibleWriteModes = possibleWriteModes.substring(2); // // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption(Option.builder("o").argName("base output dir").hasArg().desc( "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \"" + outLoc + "\".") .build()); options.addOption(Option.builder("s").argName("source name").hasArg() .desc("Name of source to write data to; default = \"" + srcName + "\".").build()); options.addOption(Option.builder("b").argName("points per block").hasArg() .desc("Number of points per block; UDP output mode will use 1 point/block; default = " + Long.toString(blockPts) + ".") .build()); options.addOption(Option.builder("dt").argName("samp interval msec").hasArg() .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build()); options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc( "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption( Option.builder("w").argName("write mode").hasArg() .desc("Type of write connection; one of " + possibleWriteModes + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".") .build()); options.addOption(Option.builder("host").argName("host[:port]").hasArg() .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build()); options.addOption(Option.builder("u").argName("username,password").hasArg() .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build()); options.addOption("x", "debug", false, "Enable CloudTurbine debug output."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("CTmousetrack", "", options, "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port."); return; } outLoc = line.getOptionValue("o", outLoc); if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) { outLoc = outLoc + File.separator; } // Make sure the base output folder location ends in "CTdata" if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) { outLoc = outLoc + "CTdata" + File.separator; } srcName = line.getOptionValue("s", srcName); blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts))); sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval))); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); // Type of output connection String writeModeStr = line.getOptionValue("w", writeMode.name()); boolean bMatch = false; for (CTWriteMode wm : CTWriteMode.values()) { if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) { writeMode = wm; bMatch = true; } } if (!bMatch) { System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of " + possibleWriteModes); System.exit(0); } if (writeMode != CTWriteMode.LOCAL) { // User must have specified the host // If FTP or HTTPS, they may also specify username/password serverHost = line.getOptionValue("host", serverHost); if (serverHost.isEmpty()) { System.err.println( "When using write mode \"" + writeModeStr + "\", you must specify the server host."); System.exit(0); } if (writeMode == CTWriteMode.UDP) { // Force blockPts to be 1 blockPts = 1; // User must have specified both host and port int colonIdx = serverHost.indexOf(':'); if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) { System.err.println( "For UDP output mode, both the host and port (<host>:<port>)) must be specified."); System.exit(0); } udpHost = serverHost.substring(0, colonIdx); String udpPortStr = serverHost.substring(colonIdx + 1); try { udpPort = Integer.parseInt(udpPortStr); } catch (NumberFormatException nfe) { System.err.println("The UDP port must be a positive integer."); System.exit(0); } } if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) { String userpassStr = line.getOptionValue("u", ""); if (!userpassStr.isEmpty()) { // This string should be comma-delimited username and password String[] userpassCSV = userpassStr.split(","); if (userpassCSV.length != 2) { System.err.println("When specifying a username and password for write mode \"" + writeModeStr + "\", separate the username and password by a comma."); System.exit(0); } serverUser = userpassCSV[0]; serverPassword = userpassCSV[1]; } } } debug = line.hasOption("debug"); System.err.println("CTmousetrack parameters:"); System.err.println("\toutput mode = " + writeMode.name()); if (writeMode == CTWriteMode.UDP) { System.err.println("\twrite to " + udpHost + ":" + udpPort); } else { System.err.println("\tsource = " + srcName); System.err.println("\ttrim time = " + trimTime + " sec"); } System.err.println("\tpoints per block = " + blockPts); System.err.println("\tsample interval = " + sampInterval + " msec"); try { // // Setup CTwriter or UDP output // CTwriter ctw = null; CTinfo.setDebug(debug); if (writeMode == CTWriteMode.LOCAL) { ctw = new CTwriter(outLoc + srcName, trimTime); System.err.println("\tdata will be written to local folder \"" + outLoc + "\""); } else if (writeMode == CTWriteMode.FTP) { CTftp ctftp = new CTftp(srcName); try { ctftp.login(serverHost, serverUser, serverPassword); } catch (Exception e) { throw new IOException( new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage())); } ctw = ctftp; // upcast to CTWriter System.err.println("\tdata will be written to FTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTP) { // Don't send username/pw in HTTP mode since they will be unencrypted CThttp cthttp = new CThttp(srcName, "http://" + serverHost); ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTP server at " + serverHost); } else if (writeMode == CTWriteMode.HTTPS) { CThttp cthttp = new CThttp(srcName, "https://" + serverHost); // Username/pw are optional for HTTPS mode; only use them if username is not empty if (!serverUser.isEmpty()) { try { cthttp.login(serverUser, serverPassword); } catch (Exception e) { throw new IOException(new String( "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage())); } } ctw = cthttp; // upcast to CTWriter System.err.println("\tdata will be written to HTTPS server at " + serverHost); } else if (writeMode == CTWriteMode.UDP) { try { udpServerSocket = new DatagramSocket(); } catch (SocketException se) { System.err.println("Error creating socket for UDP:\n" + se); System.exit(0); } try { udpServerAddress = InetAddress.getByName(udpHost); } catch (UnknownHostException uhe) { System.err.println("Error getting UDP server host address:\n" + uhe); System.exit(0); } } if (writeMode != CTWriteMode.UDP) { ctw.setBlockMode(blockPts > 1, blockPts > 1); ctw.autoFlush(0); // no autoflush ctw.autoSegment(1000); } // screen dims Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); double width = screenSize.getWidth(); double height = screenSize.getHeight(); // use Map for consolidated putData Map<String, Object> cmap = new LinkedHashMap<String, Object>(); // loop and write some output for (int i = 0; i < 1000000; i++) { // go until killed long currentTime = System.currentTimeMillis(); Point mousePos = MouseInfo.getPointerInfo().getLocation(); float x_pt = (float) (mousePos.getX() / width); // normalize float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0) if (writeMode != CTWriteMode.UDP) { // CT output mode ctw.setTime(currentTime); cmap.clear(); cmap.put("x", x_pt); cmap.put("y", y_pt); ctw.putData(cmap); if (((i + 1) % blockPts) == 0) { ctw.flush(); System.err.print("."); } } else { // UDP output mode // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time // Write the following data (21 bytes total): // header = "MOUSE", 5 bytes // current time, long, 8 bytes // 2 floats (x,y) 4 bytes each, 8 bytes int len = 21; ByteBuffer bb = ByteBuffer.allocate(len); String headerStr = "MOUSE"; bb.put(headerStr.getBytes("UTF-8")); bb.putLong(currentTime); bb.putFloat(x_pt); bb.putFloat(y_pt); // Might be able to use the following, but not sure: // byte[] sendData = bb.array(); byte[] sendData = new byte[len]; bb.position(0); bb.get(sendData, 0, len); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress, udpPort); try { udpServerSocket.send(sendPacket); } catch (IOException e) { System.err.println("Test server caught exception trying to send data to UDP client:\n" + e); } System.err.print("."); } try { Thread.sleep(sampInterval); } catch (Exception e) { } ; } if (writeMode != CTWriteMode.UDP) { ctw.flush(); // wrap up } } catch (Exception e) { System.err.println("CTmousetrack exception: " + e); e.printStackTrace(); } }
From source file:com.netscape.cmstools.CRMFPopClient.java
public static void main(String args[]) throws Exception { Options options = createOptions();/* w ww .j av a 2 s .c o m*/ CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e.getMessage()); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String tokenPassword = cmd.getOptionValue("p"); String tokenName = cmd.getOptionValue("h"); String algorithm = cmd.getOptionValue("a", "rsa"); int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048")); String profileID = cmd.getOptionValue("f"); String subjectDN = cmd.getOptionValue("n"); boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false")); // if transportCertFilename is not specified then assume no key archival String transportCertFilename = cmd.getOptionValue("b"); String popOption = cmd.getOptionValue("q", "POP_SUCCESS"); String curve = cmd.getOptionValue("c", "nistp256"); boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false")); boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true")); int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1")); int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1")); boolean self_sign = cmd.hasOption("y"); // get the keywrap algorithm KeyWrapAlgorithm keyWrapAlgorithm = null; String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString(); if (cmd.hasOption("w")) { kwAlg = cmd.getOptionValue("w"); } else { String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM"); if (alg != null) { kwAlg = alg; } } String output = cmd.getOptionValue("o"); String hostPort = cmd.getOptionValue("m"); String username = cmd.getOptionValue("u"); String requestor = cmd.getOptionValue("r"); if (hostPort != null) { if (cmd.hasOption("w")) { printError("Any value specified for the key wrap parameter (-w) " + "will be overriden. CRMFPopClient will contact the " + "CA to determine the supported algorithm when " + "hostport is specified"); } } if (subjectDN == null) { printError("Missing subject DN"); System.exit(1); } if (tokenPassword == null) { printError("Missing token password"); System.exit(1); } if (algorithm.equals("rsa")) { if (cmd.hasOption("c")) { printError("Illegal parameter for RSA: -c"); System.exit(1); } if (cmd.hasOption("t")) { printError("Illegal parameter for RSA: -t"); System.exit(1); } if (cmd.hasOption("s")) { printError("Illegal parameter for RSA: -s"); System.exit(1); } if (cmd.hasOption("e")) { printError("Illegal parameter for RSA: -e"); System.exit(1); } if (cmd.hasOption("x")) { printError("Illegal parameter for RSA: -x"); System.exit(1); } } else if (algorithm.equals("ec")) { if (cmd.hasOption("l")) { printError("Illegal parameter for ECC: -l"); System.exit(1); } if (sensitive != 0 && sensitive != 1 && sensitive != -1) { printError("Illegal input parameters for -s: " + sensitive); System.exit(1); } if (extractable != 0 && extractable != 1 && extractable != -1) { printError("Illegal input parameters for -e: " + extractable); System.exit(1); } } else { printError("Invalid algorithm: " + algorithm); System.exit(1); } if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) { printError("Invalid POP option: " + popOption); System.exit(1); } if (profileID == null) { if (algorithm.equals("rsa")) { profileID = "caEncUserCert"; } else if (algorithm.equals("ec")) { profileID = "caEncECUserCert"; } else { throw new Exception("Unknown algorithm: " + algorithm); } } try { if (verbose) System.out.println("Initializing security database: " + databaseDir); CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); try { token.login(password); } catch (Exception e) { throw new Exception("Unable to login: " + e, e); } CRMFPopClient client = new CRMFPopClient(); client.setVerbose(verbose); String encoded = null; X509Certificate transportCert = null; if (transportCertFilename != null) { if (verbose) System.out.println("archival option enabled"); if (verbose) System.out.println("Loading transport certificate"); encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename))); byte[] transportCertData = Cert.parseCertificate(encoded); transportCert = manager.importCACertPackage(transportCertData); } else { if (verbose) System.out.println("archival option not enabled"); } if (verbose) System.out.println("Parsing subject DN"); Name subject = client.createName(subjectDN, encodingEnabled); if (subject == null) { subject = new Name(); subject.addCommonName("Me"); subject.addCountryName("US"); subject.addElement( new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid"))); } if (verbose) System.out.println("Generating key pair"); KeyPair keyPair; if (algorithm.equals("rsa")) { keyPair = CryptoUtil.generateRSAKeyPair(token, keySize); } else if (algorithm.equals("ec")) { keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable); } else { throw new Exception("Unknown algorithm: " + algorithm); } // print out keyid to be used in cmc decryptPOP PrivateKey privateKey = (PrivateKey) keyPair.getPrivate(); @SuppressWarnings("deprecation") byte id[] = privateKey.getUniqueID(); String kid = CryptoUtil.encodeKeyID(id); System.out.println("Keypair private key id: " + kid); if ((transportCert != null) && (hostPort != null)) { // check the CA for the required key wrap algorithm // if found, override whatever has been set by the command line // options for the key wrap algorithm ClientConfig config = new ClientConfig(); String host = hostPort.substring(0, hostPort.indexOf(':')); int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1)); config.setServerURL("http", host, port); PKIClient pkiclient = new PKIClient(config); kwAlg = getKeyWrapAlgotihm(pkiclient); } if (verbose && (transportCert != null)) System.out.println("Using key wrap algorithm: " + kwAlg); if (transportCert != null) { keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg); } if (verbose) System.out.println("Creating certificate request"); CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair, subject, keyWrapAlgorithm); ProofOfPossession pop = null; if (!popOption.equals("POP_NONE")) { if (verbose) System.out.println("Creating signer"); Signature signer = client.createSigner(token, algorithm, keyPair); if (popOption.equals("POP_SUCCESS")) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); certRequest.encode(bo); signer.update(bo.toByteArray()); } else if (popOption.equals("POP_FAIL")) { byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; signer.update(data); } byte[] signature = signer.sign(); if (verbose) System.out.println("Creating POP"); pop = client.createPop(algorithm, signature); } if (verbose) System.out.println("Creating CRMF request"); String request = client.createCRMFRequest(certRequest, pop); StringWriter sw = new StringWriter(); try (PrintWriter out = new PrintWriter(sw)) { out.println(Cert.REQUEST_HEADER); out.print(request); out.println(Cert.REQUEST_FOOTER); } String csr = sw.toString(); if (hostPort != null) { System.out.println("Submitting CRMF request to " + hostPort); client.submitRequest(request, hostPort, username, profileID, requestor); } else if (output != null) { System.out.println("Storing CRMF request into " + output); try (FileWriter out = new FileWriter(output)) { out.write(csr); } } else { System.out.println(csr); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }