List of usage examples for org.apache.commons.codec.binary Base64 Base64
public Base64()
From source file:com.ning.metrics.eventtracker.ScribeSender.java
protected static String eventToLogEntryMessage(Event event) throws IOException { // Has the sender specified how to send the data? byte[] payload = event.getSerializedEvent(); // Nope, default to ObjectOutputStream if (payload == null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); event.writeExternal(new ObjectOutputStream(out)); payload = out.toByteArray();/*from w w w. j a va 2 s . com*/ // 64-bit encode the serialized object payload = new Base64().encode(payload); } String scribePayload = new String(payload, CHARSET); // TODO Ugly code... if (event instanceof SmileBucketEvent) { return scribePayload; } else { // To avoid costly Thrift deserialization on the collector side, we embed the // timestamp in the format, outside of the payload. We need it for HDFS routing. return String.format("%s:%s", event.getEventDateTime().getMillis(), scribePayload); } }
From source file:fi.aalto.seqpig.filter.CoordinateFilter.java
public CoordinateFilter(String samfileheaderfilename, String regions_str) { String str = ""; this.samfileheader = ""; this.regions_str = regions_str; try {/* www . j a v a 2 s .co m*/ Configuration conf = UDFContext.getUDFContext().getJobConf(); if (conf == null) { decodeSAMFileHeader(); return; } FileSystem fs; try { if (FileSystem.getDefaultUri(conf) == null || FileSystem.getDefaultUri(conf).toString() == "") fs = FileSystem.get(new URI("hdfs://"), conf); else fs = FileSystem.get(conf); } catch (Exception e) { fs = FileSystem.get(new URI("hdfs://"), conf); System.out.println("WARNING: problems with filesystem config?"); System.out.println("exception was: " + e.toString()); } BufferedReader in = new BufferedReader(new InputStreamReader( fs.open(new Path(fs.getHomeDirectory(), new Path(samfileheaderfilename))))); while (true) { str = in.readLine(); if (str == null) break; else this.samfileheader += str + "\n"; } in.close(); } catch (Exception e) { System.out.println("ERROR: could not read BAM header from file " + samfileheaderfilename); System.out.println("exception was: " + e.toString()); } try { Base64 codec = new Base64(); Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass()); ByteArrayOutputStream bstream = new ByteArrayOutputStream(); ObjectOutputStream ostream = new ObjectOutputStream(bstream); ostream.writeObject(this.samfileheader); ostream.close(); String datastr = codec.encodeBase64String(bstream.toByteArray()); p.setProperty("samfileheader", datastr); p.setProperty("regionsstr", regions_str); } catch (Exception e) { System.out.println("ERROR: Unable to store SAMFileHeader in CoordinateFilter!"); } this.samfileheader_decoded = getSAMFileHeader(); populateRegions(); }
From source file:jlib.xml.XMLUtil.java
public static byte[] decode64(String cs) { Base64 base64 = new Base64(); byte[] arrBytes = cs.getBytes(); return base64.decode(arrBytes); }
From source file:com.forsrc.utils.AesUtils.java
/** * Encrypt string.//from w ww.ja va 2 s .c om * * @param src the src * @return String string * @throws AesException the aes exception * @Title: encrypt * @Description: */ public String encrypt(String src) throws AesException { Cipher cipher = null; try { cipher = Cipher.getInstance(CIPHER_KEY); } catch (NoSuchAlgorithmException e) { throw new AesException(e); } catch (NoSuchPaddingException e) { throw new AesException(e); } byte[] raw = KEY.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(raw, SECRET_KEY); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER.getBytes()); try { cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); } catch (InvalidKeyException e) { throw new AesException(e); } catch (InvalidAlgorithmParameterException e) { throw new AesException(e); } byte[] encrypted; try { encrypted = cipher.doFinal(src.getBytes(CHARSET_UTF8)); } catch (IllegalBlockSizeException e) { throw new AesException(e); } catch (BadPaddingException e) { throw new AesException(e); } catch (UnsupportedEncodingException e) { throw new AesException(e); } return new String(new Base64().encode(encrypted)); }
From source file:com.mb.framework.util.SecurityUtil.java
/** * //from w w w. java 2 s . c o m * This method is used for encrypt by using Algorithm - AES/CBC/PKCS5Padding * * @param String * @return String * @throws Exception */ public static String encryptAESPBKDF2(String plainText) throws Exception { // get salt salt = generateSaltAESPBKDF2(); byte[] saltBytes = salt.getBytes("UTF-8"); // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); // encrypt the message Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV(); byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8")); return new Base64().encodeAsString(encryptedTextBytes); }
From source file:com.shuffle.bitcoin.blockchain.Btcd.java
/** * This method will take in an address hash and return a List of all transactions associated with * this address. These transactions are in bitcoinj's Transaction format. *//*from www .j a va 2s . c o m*/ public synchronized List<Transaction> getAddressTransactionsInner(String address) throws IOException { List<Transaction> txList = null; String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"searchrawtransactions\", \"params\":[\"" + address + "\"]}"; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Base64 b = new Base64(); String authString = rpcuser + ":" + rpcpass; String encoding = b.encodeAsString(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length)); connection.setDoInput(true); OutputStream out = connection.getOutputStream(); out.write(requestBody.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); JSONObject json = new JSONObject(response.toString()); JSONArray jsonarray = null; txList = new LinkedList<>(); if (json.isNull("result")) { return txList; } else { jsonarray = json.getJSONArray("result"); } for (int i = 0; i < jsonarray.length(); i++) { JSONObject currentJson = jsonarray.getJSONObject(i); String txid = currentJson.get("txid").toString(); HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(currentJson.get("hex").toString()); Context context = Context.getOrCreate(netParams); int confirmations = Integer.parseInt(currentJson.get("confirmations").toString()); boolean confirmed; if (confirmations == 0) { confirmed = false; } else { confirmed = true; } org.bitcoinj.core.Transaction bitTx = new org.bitcoinj.core.Transaction(netParams, bytearray); Transaction tx = new Transaction(txid, bitTx, false, confirmed); txList.add(tx); } } out.flush(); out.close(); return txList; }
From source file:cc.arduino.utils.network.FileDownloader.java
private void downloadFile(boolean noResume) throws InterruptedException { RandomAccessFile file = null; try {//from w ww. j a v a2 s .c o m // Open file and seek to the end of it file = new RandomAccessFile(outputFile, "rw"); initialSize = file.length(); if (noResume && initialSize > 0) { // delete file and restart downloading Files.delete(outputFile.toPath()); initialSize = 0; } file.seek(initialSize); setStatus(Status.CONNECTING); Proxy proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(downloadUrl.toURI()); if ("true".equals(System.getProperty("DEBUG"))) { System.err.println("Using proxy " + proxy); } HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); setDownloaded(0); // Connect connection.connect(); int resp = connection.getResponseCode(); if (resp == HttpURLConnection.HTTP_MOVED_PERM || resp == HttpURLConnection.HTTP_MOVED_TEMP) { URL newUrl = new URL(connection.getHeaderField("Location")); proxy = new CustomProxySelector(PreferencesData.getMap()).getProxyFor(newUrl.toURI()); // open the new connnection again connection = (HttpURLConnection) newUrl.openConnection(proxy); connection.setRequestProperty("User-agent", userAgent); if (downloadUrl.getUserInfo() != null) { String auth = "Basic " + new String(new Base64().encode(downloadUrl.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", auth); } connection.setRequestProperty("Range", "bytes=" + initialSize + "-"); connection.setConnectTimeout(5000); connection.connect(); resp = connection.getResponseCode(); } if (resp < 200 || resp >= 300) { throw new IOException("Received invalid http status code from server: " + resp); } // Check for valid content length. long len = connection.getContentLength(); if (len >= 0) { setDownloadSize(len); } setStatus(Status.DOWNLOADING); synchronized (this) { stream = connection.getInputStream(); } byte buffer[] = new byte[10240]; while (status == Status.DOWNLOADING) { int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); setDownloaded(getDownloaded() + read); if (Thread.interrupted()) { file.close(); throw new InterruptedException(); } } if (getDownloadSize() != null) { if (getDownloaded() < getDownloadSize()) throw new Exception("Incomplete download"); } setStatus(Status.COMPLETE); } catch (InterruptedException e) { setStatus(Status.CANCELLED); // lets InterruptedException go up to the caller throw e; } catch (SocketTimeoutException e) { setStatus(Status.CONNECTION_TIMEOUT_ERROR); setError(e); } catch (Exception e) { setStatus(Status.ERROR); setError(e); } finally { IOUtils.closeQuietly(file); synchronized (this) { IOUtils.closeQuietly(stream); } } }
From source file:jlib.xml.XMLUtil.java
public static String decode64AsString(String cs) { Base64 base64 = new Base64(); byte[] arrBytes = cs.getBytes(); byte[] tOut = base64.decode(arrBytes); String csOut = new String(tOut); return csOut; }
From source file:com.micmiu.hive.fotmater.Base64TextInputFormat.java
/** * Workaround an incompatible change from commons-codec 1.3 to 1.4. * Since Hadoop has this jar on its classpath, we have no way of knowing * which version we are running against. *///from w ww . java 2s.c o m static Base64 createBase64() { try { // This constructor appeared in 1.4 and specifies that we do not want to // line-wrap or use any newline separator Constructor<Base64> ctor = Base64.class.getConstructor(int.class, byte[].class); return ctor.newInstance(0, null); } catch (NoSuchMethodException e) { // ie we are running 1.3 // In 1.3, this constructor has the same behavior, but in 1.4 the default // was changed to add wrapping and newlines. return new Base64(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } }
From source file:com.ligadata.EncryptUtils.EncryptionUtil.java
/** * Encode(Base64 encoding) given byte array to a string * /* w w w. j a va2 s . c o m*/ * @param bytes * : an array of bytes corresponding to string being encoded * @return String * @throws java.lang.Exception and exception is thrown */ public static String encode(byte[] bytes) throws Exception { try { Base64 base64 = new Base64(); String encoded = new String(base64.encode(bytes)); return encoded; } catch (Exception e) { logger.error("Failed to encode a byte array", e); throw e; } }