List of usage examples for java.lang String getBytes
public byte[] getBytes(Charset charset)
From source file:com.javacreed.examples.sql.Example3.java
public static void main(final String[] args) throws Exception { try (BasicDataSource dataSource = DatabaseUtils.createDataSource(); Connection connection = dataSource.getConnection()) { final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") { @Override//w w w .j a v a 2 s . c o m protected String parseRow(final ResultSet resultSet) throws Exception { try (InputStream in = new LZ4BlockInputStream(resultSet.getBinaryStream("compressed"))) { return IOUtils.toString(in, "UTF-8"); } } @Override protected void setPreparedStatement(final String data, final PreparedStatement statement) throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length()); try (OutputStream out = new LZ4BlockOutputStream(baos)) { out.write(data.getBytes("UTF-8")); } statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray())); } }; test.runTest(); } Example3.LOGGER.debug("Done"); }
From source file:com._37coins.CryptoUtils.java
/** * <p>//w ww .jav a 2s. c o m * Convenience method for hashing and verifying salted SHA-1 passwords from * the command line. This method requires <code>commons-codec-1.3.jar</code> * (or a newer version) to be on the classpath. Command line arguments are * as follows: * </p> * <ul> * <li><code>--hash <var>password</var></code> - hashes * <var>password</var></code> and prints a password digest that looks like * this: <blockquote><code>{SSHA}yfT8SRT/WoOuNuA6KbJeF10OznZmb28=</code> * </blockquote></li> * <li><code>--verify <var>password</var> <var>digest</var></code> - * verifies <var>password</var> by extracting the salt from * <var>digest</var> (which is identical to what is printed by * <code>--hash</code>) and re-computing the digest again using the password * and salt. If the password supplied is the same as the one used to create * the original digest, <code>true</code> will be printed; otherwise * <code>false</code></li> * </ul> * <p> * For example, one way to use this utility is to change to JSPWiki's * <code>build</code> directory and type the following command: * </p> * <blockquote> * <code>java -cp JSPWiki.jar:../lib/commons-codec-1.3.jar com.ecyrd.jspwiki.util.CryptoUtil --hash mynewpassword</code> * </blockquote> * * @param args * arguments for this method as described above * @throws Exception * Catches nothing; throws everything up. */ public static void main(final String[] args) throws Exception { // Print help if the user requested it, or if no arguments if (args.length == 0 || (args.length == 1 && HELP.equals(args[0]))) { System.out.println("Usage: CryptUtil [options] "); System.out.println(" --hash password create hash for password"); System.out.println(" --verify password digest verify password for digest"); System.exit(0); } // User wants to hash the password if (HASH.equals(args[0])) { if (args.length < 2) { throw new IllegalArgumentException("Error: --hash requires a 'password' argument."); } final String password = args[1].trim(); System.out.println(CryptoUtils.getSaltedPassword(password.getBytes("UTF-8"))); } // User wants to verify an existing password else if (VERIFY.equals(args[0])) { if (args.length < 3) { throw new IllegalArgumentException("Error: --hash requires 'password' and 'digest' arguments."); } final String password = args[1].trim(); final String digest = args[2].trim(); System.out.println(CryptoUtils.verifySaltedPassword(password.getBytes("UTF-8"), digest)); } else { System.out.println("Wrong usage. Try --help."); } }
From source file:act.installer.pubchem.PubchemSynonymFinder.java
public static void main(String[] args) throws Exception { org.apache.commons.cli.Options opts = new org.apache.commons.cli.Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w w w . j a v a 2s.com } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH)); if (!rocksDBFile.isDirectory()) { System.err.format("Index directory does not exist or is not a directory at '%s'", rocksDBFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } List<String> compoundIds = null; if (cl.hasOption(OPTION_PUBCHEM_COMPOUND_ID)) { compoundIds = Collections.singletonList(cl.getOptionValue(OPTION_PUBCHEM_COMPOUND_ID)); } else if (cl.hasOption(OPTION_IDS_FILE)) { File idsFile = new File(cl.getOptionValue(OPTION_IDS_FILE)); if (!idsFile.exists()) { System.err.format("Cannot find Pubchem CIDs file at %s", idsFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } compoundIds = getCIDsFromFile(idsFile); if (compoundIds.size() == 0) { System.err.format("Found zero Pubchem CIDs to process in file at '%s', exiting", idsFile.getAbsolutePath()); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } } else { System.err.format("Must specify one of '%s' or '%s'; index is too big to print all synonyms.", OPTION_PUBCHEM_COMPOUND_ID, OPTION_IDS_FILE); HELP_FORMATTER.printHelp(PubchemSynonymFinder.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Run a quick check to warn users of malformed ids. compoundIds.forEach(x -> { if (!PC_CID_PATTERN.matcher(x).matches()) { // Use matches() for complete matching. LOGGER.warn("Specified compound id does not match expected format: %s", x); } }); LOGGER.info("Opening DB and searching for %d Pubchem CIDs", compoundIds.size()); Pair<RocksDB, Map<PubchemTTLMerger.COLUMN_FAMILIES, ColumnFamilyHandle>> dbAndHandles = null; Map<String, PubchemSynonyms> results = new LinkedHashMap<>(compoundIds.size()); try { dbAndHandles = PubchemTTLMerger.openExistingRocksDB(rocksDBFile); RocksDB db = dbAndHandles.getLeft(); ColumnFamilyHandle cidToSynonymsCfh = dbAndHandles.getRight() .get(PubchemTTLMerger.COLUMN_FAMILIES.CID_TO_SYNONYMS); for (String cid : compoundIds) { PubchemSynonyms synonyms = null; byte[] val = db.get(cidToSynonymsCfh, cid.getBytes(UTF8)); if (val != null) { ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(val)); // We're relying on our use of a one-value-type per index model here so we can skip the instanceof check. synonyms = (PubchemSynonyms) oi.readObject(); } else { LOGGER.warn("No synonyms available for compound id '%s'", cid); } results.put(cid, synonyms); } } finally { if (dbAndHandles != null) { dbAndHandles.getLeft().close(); } } try (OutputStream outputStream = cl.hasOption(OPTION_OUTPUT) ? new FileOutputStream(cl.getOptionValue(OPTION_OUTPUT)) : System.out) { OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(outputStream, results); new OutputStreamWriter(outputStream).append('\n'); } LOGGER.info("Done searching for Pubchem synonyms"); }
From source file:com.doctor.base64.CommonsCodecBase64.java
public static void main(String[] args) { String plainText = "Base64??" + "??ASCII???" + "????Base64"; // ??//from ww w .j ava 2 s . c om String base64String = Base64.encodeBase64String(plainText.getBytes(StandardCharsets.UTF_8)); System.out.println(base64String); String plainTxt = new String(Base64.decodeBase64(base64String), StandardCharsets.UTF_8); Preconditions.checkArgument(plainTxt.equals(plainText)); // ?? base64String = new String(Base64.encodeBase64Chunked(plainText.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); plainTxt = new String(Base64.decodeBase64(base64String), StandardCharsets.UTF_8); Preconditions.checkArgument(plainTxt.equals(plainText)); }
From source file:asm.FindCallers.java
public static void main(String... args) { OutputStream os = null;/*from w w w .ja v a 2 s . co m*/ try { FindAnnotationWalker w = new FindAnnotationWalker(); FindCallers cl = w.walk(args[0], args[1]); for (Annotated a : cl.annotated) System.out.println(a); System.out.println("Start CSV"); os = new FileOutputStream(args[2]); for (Annotated a : cl.annotated) { if (!a.isPublic) { String line = String.format("%s\t%s\t%s\t%s\t%s\t%s\n", "no", "", "", a.className, a.name, a.getTarget()); os.write(line.getBytes("UTF-8")); } } for (Invocation i : cl.invocations) { if (cl.annotatedMap.containsKey(i.getTarget())) { for (Annotated a : cl.annotatedMap.get(i.getTarget())) { String ok = ""; if (i.sourceClassName.endsWith("Cmd") || i.sourceClassName.endsWith("Test") || i.sourceClassName.contains("/test/")) { ok = "ok"; } if (i.sourceClassName.equals(a.className)) { ok = "no"; } if (ok.equals("") && i.sourceBaseName.equals(a.baseName) && !i.sourceClassName.equals(a.className)) { /* Source and dest are different and they are both have the * same parent, so they obviously one isn't a child of the other */ ok = "ok"; } String line = String.format("%s\t%s\t%s\t%s\t%s\t%s\n", ok, i.sourceClassName, i.sourceMethodName, a.className, a.name, a.getTarget()); os.write(line.getBytes("UTF-8")); } } } System.out.println("Done CSV"); } catch (Throwable e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(os); } }
From source file:com.javacreed.examples.sql.Example4.java
public static void main(final String[] args) throws Exception { try (BasicDataSource dataSource = DatabaseUtils.createDataSource(); Connection connection = dataSource.getConnection()) { final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") { @Override/*from w w w. j ava 2s .c o m*/ protected String parseRow(final ResultSet resultSet) throws Exception { try (InputStream in = new LZ4BlockInputStream( CryptoUtils.wrapInToCipheredInputStream(resultSet.getBinaryStream("compressed")))) { return IOUtils.toString(in, "UTF-8"); } } @Override protected void setPreparedStatement(final String data, final PreparedStatement statement) throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length()); try (OutputStream out = new LZ4BlockOutputStream( CryptoUtils.wrapInToCipheredOutputStream(baos))) { out.write(data.getBytes("UTF-8")); } statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray())); } }; test.runTest(); } Example4.LOGGER.debug("Done"); }
From source file:MD5.java
public static void main(String[] args) { //String password = args[0]; String password = "test"; MessageDigest digest = null;/*from w w w . ja va 2 s . c o m*/ try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { digest.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] rawData = digest.digest(); StringBuffer printable = new StringBuffer(); for (int i = 0; i < rawData.length; i++) { printable.append(carr[((rawData[i] & 0xF0) >> 4)]); printable.append(carr[(rawData[i] & 0x0F)]); } String phpbbPassword = printable.toString(); System.out.println("PHPBB : " + phpbbPassword); System.out.println("MVNFORUM : " + getMD5_Base64(password)); System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword)); }
From source file:dhtaccess.tools.Put.java
public static void main(String[] args) { byte[] secret = null; int ttl = 3600; // parse properties Properties prop = System.getProperties(); String gateway = prop.getProperty("dhtaccess.gateway"); if (gateway == null || gateway.length() <= 0) { gateway = DEFAULT_GATEWAY;/*from w ww . j a va2s . c o m*/ } // parse options Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt"); options.addOption("s", "secret", true, "can be used to remove the value later"); options.addOption("t", "ttl", true, "how long (in seconds) to store the value"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println("There is an invalid option."); e.printStackTrace(); System.exit(1); } String optVal; if (cmd.hasOption('h')) { usage(COMMAND); System.exit(1); } optVal = cmd.getOptionValue('g'); if (optVal != null) { gateway = optVal; } optVal = cmd.getOptionValue('s'); if (optVal != null) { try { secret = optVal.getBytes(ENCODE); } catch (UnsupportedEncodingException e) { // NOTREACHED } } optVal = cmd.getOptionValue('t'); if (optVal != null) { ttl = Integer.parseInt(optVal); } args = cmd.getArgs(); // parse arguments if (args.length < 2) { usage(COMMAND); System.exit(1); } for (int index = 0; index + 1 < args.length; index += 2) { byte[] key = null, value = null; try { key = args[index].getBytes(ENCODE); value = args[index + 1].getBytes(ENCODE); } catch (UnsupportedEncodingException e1) { // NOTREACHED } // prepare for RPC DHTAccessor accessor = null; try { accessor = new DHTAccessor(gateway); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } // RPC int res = accessor.put(key, value, ttl, secret); String resultString; switch (res) { case 0: resultString = "Success"; break; case 1: resultString = "Capacity"; break; case 2: resultString = "Again"; break; default: resultString = "???"; } System.out.println(resultString + ": " + args[index] + ", " + args[index + 1]); } }
From source file:com.javacreed.examples.sql.Example2.java
public static void main(final String[] args) throws Exception { try (BasicDataSource dataSource = DatabaseUtils.createDataSource(); Connection connection = dataSource.getConnection()) { final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") { @Override//from ww w. ja va 2 s .c om protected String parseRow(final ResultSet resultSet) throws Exception { try (GZIPInputStream in = new GZIPInputStream(resultSet.getBinaryStream("compressed"))) { return IOUtils.toString(in, "UTF-8"); } } @Override protected void setPreparedStatement(final String data, final PreparedStatement statement) throws Exception { // Compress the data before inserting it. We need to compress before inserting the data to make this process // as realistic as possible. final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length()); try (OutputStream out = new GZIPOutputStream(baos, data.length())) { out.write(data.getBytes("UTF-8")); } statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray())); } }; test.runTest(); } Example2.LOGGER.debug("Done"); }
From source file:io.apicurio.studio.tools.release.ReleaseTool.java
/** * Main method.//from w w w. ja v a 2 s . c o m * @param args */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("n", "release-name", true, "The name of the new release."); options.addOption("p", "prerelease", false, "Indicate that this is a pre-release."); options.addOption("t", "release-tag", true, "The tag name of the new release."); options.addOption("o", "previous-tag", true, "The tag name of the previous release."); options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization)."); options.addOption("a", "artifact", true, "The binary release artifact (full path)."); options.addOption("d", "output-directory", true, "Where to store output file(s)."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g") || !cmd.hasOption("a")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("release-studio", options); System.exit(1); } // Arguments (command line) String releaseName = cmd.getOptionValue("n"); boolean isPrerelease = cmd.hasOption("p"); String releaseTag = cmd.getOptionValue("t"); String oldReleaseTag = cmd.getOptionValue("o"); String githubPAT = cmd.getOptionValue("g"); String artifact = cmd.getOptionValue("a"); File outputDir = new File(""); if (cmd.hasOption("d")) { outputDir = new File(cmd.getOptionValue("d")); if (!outputDir.exists()) { outputDir.mkdirs(); } } File releaseArtifactFile = new File(artifact); File releaseArtifactSigFile = new File(artifact + ".asc"); String releaseArtifact = releaseArtifactFile.getName(); String releaseArtifactSig = releaseArtifactSigFile.getName(); if (!releaseArtifactFile.isFile()) { System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath()); System.exit(1); } if (!releaseArtifactSigFile.isFile()) { System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath()); System.exit(1); } System.out.println("========================================="); System.out.println("Creating Release: " + releaseTag); System.out.println("Previous Release: " + oldReleaseTag); System.out.println(" Name: " + releaseName); System.out.println(" Artifact: " + releaseArtifact); System.out.println(" Pre-Release: " + isPrerelease); System.out.println("========================================="); String releaseNotes = ""; // Step #1 - Generate Release Notes // * Grab info about the previous release (extract publish date) // * Query all Issues for ones closed since that date // * Generate Release Notes from the resulting Issues try { System.out.println("Getting info about release " + oldReleaseTag); HttpResponse<JsonNode> response = Unirest .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag) .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get old release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for previous release " + oldReleaseTag); } System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate); List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT); System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag); System.out.println("Generating Release Notes"); releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues); System.out.println("------------ Release Notes --------------"); System.out.println(releaseNotes); System.out.println("-----------------------------------------"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String assetUploadUrl = null; // Step #2 - Create a GitHub Release try { System.out.println("\nCreating GitHub Release " + releaseTag); JSONObject body = new JSONObject(); body.put("tag_name", "v" + releaseTag); body.put("name", releaseName); body.put("body", releaseNotes); body.put("prerelease", isPrerelease); HttpResponse<JsonNode> response = Unirest .post("https://api.github.com/repos/apicurio/apicurio-studio/releases") .header("Accept", "application/json").header("Content-Type", "application/json") .header("Authorization", "token " + githubPAT).body(body).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to create release in GitHub: " + response.getStatusText()); } assetUploadUrl = response.getBody().getObject().getString("upload_url"); if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) { throw new Exception("Failed to get Asset Upload URL for newly created release!"); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Step #3 - Upload Release Artifact (zip file) System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact); try { String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact); byte[] artifactData = loadArtifactData(releaseArtifactFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl).header("Accept", "application/json") .header("Content-Type", "application/zip").header("Authorization", "token " + githubPAT) .body(artifactData).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifact, new Exception(response.getStatus() + "::" + response.getStatusText())); } Thread.sleep(1000); artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig); artifactData = loadArtifactData(releaseArtifactSigFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); response = Unirest.post(artifactUploadUrl).header("Accept", "application/json") .header("Content-Type", "text/plain").header("Authorization", "token " + githubPAT) .body(artifactData).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifactSig, new Exception(response.getStatus() + "::" + response.getStatusText())); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } Thread.sleep(1000); // Step #4 - Download Latest Release JSON for inclusion in the project web site try { System.out.println("Getting info about the release."); HttpResponse<JsonNode> response = Unirest .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest") .header("Accept", "application/json").asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for release."); } String fname = publishedDate.replace(':', '-'); File outFile = new File(outputDir, fname + ".json"); System.out.println("Writing latest release info to: " + outFile.getAbsolutePath()); String output = body.getObject().toString(4); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(output.getBytes("UTF-8")); fos.flush(); } System.out.println("Release info successfully written."); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.out.println("========================================="); System.out.println("All Done!"); System.out.println("========================================="); }