List of usage examples for java.lang String toCharArray
public char[] toCharArray()
From source file:MainClass.java
public static void main(String[] args) { String phrase = new String("text \n"); String dirname = "C:/test"; String filename = "charData.txt"; File dir = new File(dirname); File aFile = new File(dir, filename); FileOutputStream outputFile = null; try {// ww w . j a v a 2 s .c o m outputFile = new FileOutputStream(aFile, true); System.out.println("File stream created successfully."); } catch (FileNotFoundException e) { e.printStackTrace(System.err); } FileChannel outChannel = outputFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(1024); System.out.println("New buffer: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); for (char ch : phrase.toCharArray()) { buf.putChar(ch); } System.out.println("Buffer after loading: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); buf.flip(); System.out.println("Buffer after flip: position = " + buf.position() + "\tLimit = " + buf.limit() + "\tcapacity = " + buf.capacity()); try { outChannel.write(buf); outputFile.close(); System.out.println("Buffer contents written to file."); } catch (IOException e) { e.printStackTrace(System.err); } }
From source file:com.luqili.http.ssl.ClientCustomSSL.java
public final static void main(String[] args) throws Exception { String sslKeyStorePath = "/mnt/data2/clientkey/370900.pfx"; String sslKeyStorePassword = "370900"; String sslKeyStoreType = "PKCS12"; // JKS PKCS12 String sslTrustStore = "/mnt/data2/clientkey/PengeSoftOARoot.cer"; String sslTrustStorePassword = ""; String url = "https://123.57.205.217:8082/Service/UpReportInfoServiceSvr.assx/UpReportInfo"; String content = "Token=&CityCodes=370900&CountyCodes=&DealDate=2016-06-16T00:00:00&Reportor=?&NewBusinessArea=1000.88&NewBusinessAmount=9898&NewHouseArea=5000&NewHouseAmount=8000&NewHouseCount=20&OldReportor=?&OldBusinessArea=1234.56&OldBusinessAmount=80000&OldHouseArea=12580&OldHouseAmount=99999&OldHouseCount=100"; // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(), new TrustSelfSignedStrategy()) .loadKeyMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(), sslKeyStorePassword.toCharArray()) .build();/*from ww w. jav a 2 s . c o m*/ // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost httppost = new HttpPost(url); System.out.println("Executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8").trim(); if (!"True".toUpperCase().equals(result.toUpperCase())) { System.out.println(result); } } System.out.println(response.getStatusLine()); EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
From source file:createSod.java
/** * @param args/* w w w.java 2s .co m*/ * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:com.netscape.cmstools.CMCSharedToken.java
public static void main(String args[]) throws Exception { boolean isVerificationMode = false; // developer debugging only Options options = createOptions();/*w w w .ja va2 s .c om*/ 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 passphrase = cmd.getOptionValue("s"); if (passphrase == null) { printError("Missing passphrase"); System.exit(1); } if (verbose) { System.out.println("passphrase String = " + passphrase); System.out.println("passphrase UTF-8 bytes = "); System.out.println(Arrays.toString(passphrase.getBytes("UTF-8"))); } String tokenName = cmd.getOptionValue("h"); String tokenPassword = cmd.getOptionValue("p"); String issuanceProtCertFilename = cmd.getOptionValue("b"); String issuanceProtCertNick = cmd.getOptionValue("n"); String output = cmd.getOptionValue("o"); try { CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); token.login(password); X509Certificate issuanceProtCert = null; if (issuanceProtCertFilename != null) { if (verbose) System.out.println("Loading issuance protection certificate"); String encoded = new String(Files.readAllBytes(Paths.get(issuanceProtCertFilename))); byte[] issuanceProtCertData = Cert.parseCertificate(encoded); issuanceProtCert = manager.importCACertPackage(issuanceProtCertData); if (verbose) System.out.println("issuance protection certificate imported"); } else { // must have issuance protection cert nickname if file not provided if (verbose) System.out.println("Getting cert by nickname: " + issuanceProtCertNick); if (issuanceProtCertNick == null) { System.out.println( "Invallid command: either nickname or PEM file must be provided for Issuance Protection Certificate"); System.exit(1); } issuanceProtCert = getCertificate(tokenName, issuanceProtCertNick); } EncryptionAlgorithm encryptAlgorithm = EncryptionAlgorithm.AES_128_CBC_PAD; KeyWrapAlgorithm wrapAlgorithm = KeyWrapAlgorithm.RSA; if (verbose) System.out.println("Generating session key"); SymmetricKey sessionKey = CryptoUtil.generateKey(token, KeyGenAlgorithm.AES, 128, null, true); if (verbose) System.out.println("Encrypting passphrase"); byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; byte[] secret_data = CryptoUtil.encryptUsingSymmetricKey(token, sessionKey, passphrase.getBytes("UTF-8"), encryptAlgorithm, new IVParameterSpec(iv)); if (verbose) System.out.println("Wrapping session key with issuance protection cert"); byte[] issuanceProtWrappedSessionKey = CryptoUtil.wrapUsingPublicKey(token, issuanceProtCert.getPublicKey(), sessionKey, wrapAlgorithm); // final_data takes this format: // SEQUENCE { // encryptedSession OCTET STRING, // encryptedPrivate OCTET STRING // } DerOutputStream tmp = new DerOutputStream(); tmp.putOctetString(issuanceProtWrappedSessionKey); tmp.putOctetString(secret_data); DerOutputStream out = new DerOutputStream(); out.write(DerValue.tag_Sequence, tmp); byte[] final_data = out.toByteArray(); String final_data_b64 = Utils.base64encode(final_data, true); if (final_data_b64 != null) { System.out.println("\nEncrypted Secret Data:"); System.out.println(final_data_b64); } else System.out.println("Failed to produce final data"); if (output != null) { System.out.println("\nStoring Base64 secret data into " + output); try (FileWriter fout = new FileWriter(output)) { fout.write(final_data_b64); } } if (isVerificationMode) { // developer use only PrivateKey wrappingKey = null; if (issuanceProtCertNick != null) wrappingKey = (org.mozilla.jss.crypto.PrivateKey) getPrivateKey(tokenName, issuanceProtCertNick); else wrappingKey = CryptoManager.getInstance().findPrivKeyByCert(issuanceProtCert); System.out.println("\nVerification begins..."); byte[] wrapped_secret_data = Utils.base64decode(final_data_b64); DerValue wrapped_val = new DerValue(wrapped_secret_data); // val.tag == DerValue.tag_Sequence DerInputStream wrapped_in = wrapped_val.data; DerValue wrapped_dSession = wrapped_in.getDerValue(); byte wrapped_session[] = wrapped_dSession.getOctetString(); System.out.println("wrapped session key retrieved"); DerValue wrapped_dPassphrase = wrapped_in.getDerValue(); byte wrapped_passphrase[] = wrapped_dPassphrase.getOctetString(); System.out.println("wrapped passphrase retrieved"); SymmetricKey ver_session = CryptoUtil.unwrap(token, SymmetricKey.AES, 128, SymmetricKey.Usage.UNWRAP, wrappingKey, wrapped_session, wrapAlgorithm); byte[] ver_passphrase = CryptoUtil.decryptUsingSymmetricKey(token, new IVParameterSpec(iv), wrapped_passphrase, ver_session, encryptAlgorithm); String ver_spassphrase = new String(ver_passphrase, "UTF-8"); CryptoUtil.obscureBytes(ver_passphrase, "random"); System.out.println("ver_passphrase String = " + ver_spassphrase); System.out.println("ver_passphrase UTF-8 bytes = "); System.out.println(Arrays.toString(ver_spassphrase.getBytes("UTF-8"))); if (ver_spassphrase.equals(passphrase)) System.out.println("Verification success!"); else System.out.println("Verification failure! ver_spassphrase=" + ver_spassphrase); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }
From source file:com.daon.identityx.utils.GenerateAndroidFacet.java
public static void main(String[] args) { String androidKeystoreLocation = System.getProperty("ANDROID_KEYSTORE_LOCATION", DEFAULT_ANDROID_KEYSTORE_LOCATION); String androidKeystorePassword = System.getProperty("ANDROID_KEYSTORE_PASSWORD", DEFAULT_ANDROID_KEYSTORE_PASSWORD); String androidKeystoreCert = System.getProperty("ANDROID_KEYSTORE_CERT_NAME", DEFAULT_ANDROID_KEYSTORE_CERT_NAME); String hashingAlgorithm = System.getProperty("HASHING_ALGORITHM", DEFAULT_HASHING_ALGORITHM); try {// w w w . java 2 s . c o m KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); File filePath = new File(androidKeystoreLocation); if (!filePath.exists()) { System.err.println( "The filepath to the debug keystore could not be located at: " + androidKeystoreCert); System.exit(1); } else { System.out.println("Found the Android Studio keystore at: " + androidKeystoreLocation); } keyStore.load(new FileInputStream(filePath), androidKeystorePassword.toCharArray()); System.out.println("Keystore loaded - password and location were OK"); Certificate cert = keyStore.getCertificate(androidKeystoreCert); if (cert == null) { System.err.println( "Could not location the certification in the store with the name: " + androidKeystoreCert); System.exit(1); } else { System.out.println("Certificate found in the store with name: " + androidKeystoreCert); } byte[] certBytes = cert.getEncoded(); MessageDigest digest = MessageDigest.getInstance(hashingAlgorithm); System.out.println("Hashing algorithm: " + hashingAlgorithm + " found."); byte[] hashedCert = digest.digest(certBytes); String base64HashedCert = Base64.getEncoder().encodeToString(hashedCert); System.out.println("Base64 encoded SHA-1 hash of the certificate: " + base64HashedCert); String base64HashedCertRemoveTrailing = StringUtils.deleteAny(base64HashedCert, "="); System.out.println( "Add the following facet to the Facets file in order for the debug app to be trusted by the FIDO client"); System.out.println("\"android:apk-key-hash:" + base64HashedCertRemoveTrailing + "\""); } catch (Throwable ex) { ex.printStackTrace(); } }
From source file:com.board.games.handler.modx.MODXPokerLoginServiceImpl.java
public static void main(String[] a) { Verifier verifier = new Verifier(); String dbHash = "iDxLTbkejeeaQqpPoZTqUCJfWo1ALcBf7gMlYwwMa+Y="; //"dlgQ65ruCfeVVxqHJ3Bf02j50P0Wvis7WOoTfHYV3Nk="; String password = "rememberme"; String dbSalt = "008747a35b77a4c7e55ab7ea8aec3ee0"; PasswordResponse response = new PasswordResponse(); String salt = "008747a35b77a4c7e55ab7ea8aec3ee0"; response.setAlgorithm(Algorithm.PBKDF2); response.setSalt(salt);/*from w ww. ja v a2 s . c o m*/ response.setAlgorithmDetails(new AlgorithmDetails()); response.getAlgorithmDetails().setIterations(1000); response.getAlgorithmDetails().setHashFunction("SHA256"); response.getAlgorithmDetails().setKeySize(263); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000, response.getAlgorithmDetails().getKeySize()); try { SecretKeyFactory skf = PBKDF2Algorithms.getSecretKeyFactory( "PBKDF2WithHmac" + response.getAlgorithmDetails().getHashFunction().replace("-", "")); byte[] hash = skf.generateSecret(spec).getEncoded(); String encodedHash = Base64.encodeBase64String(hash); response.setHash(encodedHash); System.out.println("hash " + response.getHash()); if (verifier.verify(password, response)) { // Check it against database stored hash if (encodedHash.equals(dbHash)) { System.out.println("Authentication Successful"); } else { System.out.println("Authentication failed"); } } else { System.out.println("failed verification of hashing"); } } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:SftpClientFactory.java
public static void main(String args[]) throws FileSystemException { String hostName = "commentpool-baggio000.rhcloud.com"; String username = "529ddb964382eca06f0004b0"; String password = "1026wu"; // Create SFTP options FileSystemOptions opts = new FileSystemOptions(); // // SSH Key checking // SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking( // opts, "yes"); ///*from w w w. ja v a2 s .c o m*/ // // Root directory set to user home // SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); // // // Timeout is count by Milliseconds // SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000); SftpFileSystemConfigBuilder.getInstance().setIdentities(opts, new File[] { new File("baggio_openssh.ppk") }); createConnection(hostName, 22, username.toCharArray(), password.toCharArray(), opts); }
From source file:ImportKey.java
/** * <p>/* ww w. j a v a 2s. c o m*/ * Takes two file names for a key and the certificate for the key, and * imports those into a keystore. Optionally it takes an alias for the key. * <p> * The first argument is the filename for the key. The key should be in * PKCS8-format. * <p> * The second argument is the filename for the certificate for the key. * <p> * If a third argument is given it is used as the alias. If missing, the key * is imported with the alias importkey * <p> * The name of the keystore file can be controlled by setting the keystore * property (java -Dkeystore=mykeystore). If no name is given, the file is * named <code>keystore.ImportKey</code> and placed in your home directory. * * @param args * [0] Name of the key file, [1] Name of the certificate file [2] * Alias for the key. **/ public static void main(String args[]) { // change this if you want another password by default String keypass = "password"; // change this if you want another alias by default String defaultalias = "tomcat"; // change this if you want another keystorefile by default String keystorename = null; // parsing command line input String keyfile = ""; String certfile = ""; if (args.length < 3 || args.length > 4) { System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]"); System.exit(0); } else { keystorename = args[0]; keyfile = args[1]; certfile = args[2]; if (args.length > 3) defaultalias = args[3]; } try { // initializing and clearing keystore KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, keypass.toCharArray()); System.out.println("Using keystore-file : " + keystorename); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); ks.load(new FileInputStream(keystorename), keypass.toCharArray()); // loading Key InputStream fl = fullStream(keyfile); byte[] key = new byte[fl.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); fl.read(key, 0, fl.available()); fl.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key); PrivateKey ff = kf.generatePrivate(keysp); // loading CertificateChain CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certstream = fullStream(certfile); Collection c = cf.generateCertificates(certstream); Certificate[] certs = new Certificate[c.toArray().length]; if (c.size() == 1) { certstream = fullStream(certfile); System.out.println("One certificate, no chain."); Certificate cert = cf.generateCertificate(certstream); certs[0] = cert; } else { System.out.println("Certificate chain length: " + c.size()); certs = (Certificate[]) c.toArray(new Certificate[c.size()]); } // storing keystore ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs); System.out.println("Key and certificate stored."); System.out.println("Alias:" + defaultalias + " Password:" + keypass); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.wandrell.util.ksgen.KeyStoreGenerator.java
/** * Runs the generator and creates a new set of key stores. * * @param args/*w w w . ja va 2 s.c o m*/ * the arguments * @throws Exception * if any problem occurs while generating the key stores */ public static final void main(final String[] args) throws Exception { final KeyStore jksMain; // Main key store final KeyStore jksSecond; // Second key store final KeyStore jceksSym; // Symmetric key store final String jksMainPath; // Path for the main key store final String jksSecondPath; // Path for the second key store final String jceksSymPath; // Path for the symmetric key store final String password; // Password to apply to the key stores final String alias; // Alias for the certificate final String issuer; // Issuer for the certificate final KeyStoreFactory factory; // KS factory factory = new BouncyCastleKeyStoreFactory(); jksMainPath = "src/main/resources/keystore.jks"; jksSecondPath = "src/main/resources/keystore2.jks"; jceksSymPath = "src/main/resources/symmetric.jceks"; password = "123456"; alias = "swss-cert"; issuer = "CN=www.wandrell.com, O=Wandrell, OU=None, L=London, ST=England, C=UK"; Security.addProvider(new BouncyCastleProvider()); // Main key store LOGGER.trace("Creating main key store"); jksMain = factory.getJavaKeyStore(password, alias, issuer); // Saves the main keystore saveToFile(jksMain, jksMainPath, password.toCharArray()); LOGGER.trace("Created main key store"); // Second key store LOGGER.trace("Creating second key store"); jksSecond = factory.getJavaKeyStore(password, alias, issuer); // Saves the second key store saveToFile(jksSecond, jksSecondPath, password.toCharArray()); LOGGER.trace("Created second key store"); // Symmetric key store LOGGER.trace("Creating symmetric key store"); jceksSym = factory.getJavaCryptographicExtensionKeyStore(password, alias); // Saves the symmetric key store saveToFile(jceksSym, jceksSymPath, password.toCharArray()); LOGGER.trace("Created symmetric key store"); LOGGER.trace("Finished creating key stores"); }
From source file:Gen.java
public static void main(String[] args) throws Exception { try {/*from w ww . jav a2 s . c o m*/ File[] files = null; if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) { files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toUpperCase().endsWith(".XML"); }; }); } else { String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("") ? System.getProperty("file") : "rjmap.xml"; files = new File[] { new File(fileName) }; } log.info("files : " + Arrays.toString(files)); if (files == null || files.length == 0) { log.info("no files to parse"); System.exit(0); } boolean formatsource = true; if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("") && System.getProperty("formatsource").equalsIgnoreCase("false")) { formatsource = false; } GEN_ROOT = System.getProperty("outputdir"); if (GEN_ROOT == null || GEN_ROOT.equals("")) { GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib"; } GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/'); if (GEN_ROOT.endsWith("/")) GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1); System.out.println("GEN ROOT:" + GEN_ROOT); MAPPING_JAR_NAME = System.getProperty("mappingjar") != null && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar") : "mapping.jar"; if (!MAPPING_JAR_NAME.endsWith(".jar")) MAPPING_JAR_NAME += ".jar"; GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src"; GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + ""; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); domFactory.setValidating(false); DocumentBuilder documentBuilder = domFactory.newDocumentBuilder(); for (int f = 0; f < files.length; ++f) { log.info("parsing file : " + files[f]); Document document = documentBuilder.parse(files[f]); Vector<Node> initNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript", initNodes); for (int i = 0; i < initNodes.size(); ++i) { NamedNodeMap attrs = initNodes.elementAt(i).getAttributes(); boolean embed = attrs.getNamedItem("embed") != null && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true"); StringBuffer vbuffer = new StringBuffer(); if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue()); vbuffer.append('\n'); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } vbuffer.append(Utils.getFileAsStringBuffer(fname)); } initScriptBuffer.append(vbuffer); if (embed) embedScriptBuffer.append(vbuffer); } Vector<Node> packageInitNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript", packageInitNodes); for (int i = 0; i < packageInitNodes.size(); ++i) { NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes(); String packageName = attrs.getNamedItem("package").getNodeValue(); if (packageName.equals("")) packageName = "rGlobalEnv"; if (!packageName.endsWith("Function")) packageName += "Function"; if (packageEmbedScriptHashMap.get(packageName) == null) { packageEmbedScriptHashMap.put(packageName, new StringBuffer()); } StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName); // if (!packageName.equals("rGlobalEnvFunction")) { // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n"); // } if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname); vbuffer.append(fileBuffer); initScriptBuffer.append(fileBuffer); } } Vector<Node> functionsNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function", functionsNodes); for (int i = 0; i < functionsNodes.size(); ++i) { NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes(); String functionName = attrs.getNamedItem("name").getNodeValue(); boolean forWeb = attrs.getNamedItem("forWeb") != null && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true"); String signature = (attrs.getNamedItem("signature") == null ? "" : attrs.getNamedItem("signature").getNodeValue() + ","); String renameTo = (attrs.getNamedItem("renameTo") == null ? null : attrs.getNamedItem("renameTo").getNodeValue()); HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName); if (sigMap == null) { sigMap = new HashMap<String, FAttributes>(); Globals._functionsToPublish.put(functionName, sigMap); if (attrs.getNamedItem("returnType") == null) { _functionsVector.add(new String[] { functionName }); } else { _functionsVector.add( new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() }); } } sigMap.put(signature, new FAttributes(renameTo, forWeb)); if (forWeb) _webPublishingEnabled = true; } if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("") && System.getProperty("targetjdk").compareTo("1.5") < 0) { if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) { log.info("be careful, web publishing disabled beacuse target JDK<1.5"); } _webPublishingEnabled = false; } else { if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("") || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) { _webPublishingEnabled = true; } if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) { log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use"); _webPublishingEnabled = false; } } Vector<Node> s4Nodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes); if (s4Nodes.size() > 0) { String formalArgs = ""; String signature = ""; for (int i = 0; i < s4Nodes.size(); ++i) { NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes(); String s4Name = attrs.getNamedItem("name").getNodeValue(); formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ","); signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ","); } String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER + "', signature(" + signature + ") , function(" + formalArgs + ") { })"; initScriptBuffer.append(genBeansScriptlet); _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" }); } } if (!new File(GEN_ROOT_LIB).exists()) regenerateDir(GEN_ROOT_LIB); else { clean(GEN_ROOT_LIB, true); } for (int i = 0; i < rwebservicesScripts.length; ++i) DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]); String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() { public void run(Rengine e) { DirectJNI.getInstance().toggleMarker(); DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString()); log.info(" init script status : " + DirectJNI.getInstance().cutStatusSinceMarker()); for (int i = 0; i < _functionsVector.size(); ++i) { String[] functionPair = _functionsVector.elementAt(i); log.info("dealing with : " + functionPair[0]); regenerateDir(GEN_ROOT_SRC); String createMapStr = "createMap("; boolean isGeneric = e.rniGetBoolArrayI( e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1; log.info("is Generic : " + isGeneric); if (isGeneric) { createMapStr += functionPair[0]; } else { createMapStr += "\"" + functionPair[0] + "\""; } createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\""; createMapStr += ", typeMode=\"robject\""; createMapStr += (functionPair.length == 1 || functionPair[1] == null || functionPair[1].trim().equals("") ? "" : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1] + "\")"); createMapStr += ")"; log.info("------------------------------------------"); log.info("-- createMapStr=" + createMapStr); DirectJNI.getInstance().toggleMarker(); e.rniEval(e.rniParse(createMapStr, 1), 0); String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker(); log.info(" createMap status : " + createMapStatus); log.info("------------------------------------------"); deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms"); compile(GEN_ROOT_SRC); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null); URL url = null; try { url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar") .replace('\\', '/') + "!/"); } catch (Exception ex) { ex.printStackTrace(); } DirectJNI.generateMaps(url, true); } } }); log.info(lastStatus); log.info(DirectJNI._rPackageInterfacesHash); regenerateDir(GEN_ROOT_SRC); for (int i = 0; i < _functionsVector.size(); ++i) { unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC); } regenerateRPackageClass(true); generateS4BeanRef(); if (formatsource) applyJalopy(GEN_ROOT_SRC); compile(GEN_ROOT_SRC); for (String k : DirectJNI._rPackageInterfacesHash.keySet()) { Rmic rmicTask = new Rmic(); rmicTask.setProject(_project); rmicTask.setTaskName("rmic_packages"); rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC)); rmicTask.setBase(new File(GEN_ROOT_SRC)); rmicTask.setClassname(k + "ImplRemote"); rmicTask.init(); rmicTask.execute(); } // DirectJNI._rPackageInterfacesHash=new HashMap<String, // Vector<Class<?>>>(); // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new // Vector<Class<?>>()); if (_webPublishingEnabled) { jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null); URL url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/"); ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader()); for (String className : DirectJNI._rPackageInterfacesHash.keySet()) { if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0) continue; log.info("######## " + className); WsGen wsgenTask = new WsGen(); wsgenTask.setProject(_project); wsgenTask.setTaskName("wsgen"); FileSet rjb_fileSet = new FileSet(); rjb_fileSet.setProject(_project); rjb_fileSet.setDir(new File(".")); rjb_fileSet.setIncludes("RJB.jar"); DirSet src_dirSet = new DirSet(); src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); Path classPath = new Path(_project); classPath.addFileset(rjb_fileSet); classPath.addDirset(src_dirSet); wsgenTask.setClasspath(classPath); wsgenTask.setKeep(true); wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setSei(className + "Web"); wsgenTask.init(); wsgenTask.execute(); } new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete(); } embedRScripts(); HashMap<String, String> marker = new HashMap<String, String>(); marker.put("RJBMAPPINGJAR", "TRUE"); Properties props = new Properties(); props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames)); props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping)); props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert)); props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping)); props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash)); props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash)); props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories)); new File(GEN_ROOT_SRC + "/" + "maps").mkdirs(); FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml"); props.storeToXML(fos, null); fos.close(); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker); if (_webPublishingEnabled) genWeb(); DirectJNI._mappingClassLoader = null; } finally { System.exit(0); } }