下面列出了 org.apache.commons.codec.binary.StringUtils # newStringUtf8 ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public KafkaProduceOffsetFetcher(String zkHost) {
this.zkClient = new ZkClient(zkHost, SESSION_TIMEOUT, CONNECTION_TIMEOUT, new ZkSerializer() {
@Override
public byte[] serialize(Object o) throws ZkMarshallingError {
return ((String) o).getBytes();
}
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
if (bytes == null) {
return null;
} else {
return StringUtils.newStringUtf8(bytes);
}
}
});
}
public KafkaProduceOffsetFetcher(String zkHost) {
this.zkClient = new ZkClient(zkHost, SESSION_TIMEOUT, CONNECTION_TIMEOUT, new ZkSerializer() {
@Override
public byte[] serialize(Object o) throws ZkMarshallingError {
return ((String) o).getBytes();
}
@Override
public Object deserialize(byte[] bytes) throws ZkMarshallingError {
if (bytes == null) {
return null;
} else {
return StringUtils.newStringUtf8(bytes);
}
}
});
}
@Override
public Object decrypt(String data) {
String[] splitData = org.apache.commons.lang3.StringUtils.split(data, ':');
// String[] splitData = data.split(":");
if (splitData.length != 2) {
return null;
} else {
if (splitData[0].equals("ESTRING")) {
return StringUtils.newStringUtf8(decryptToBytes(splitData[1]));
} else if (splitData[0].equals("EBOOL")) {
return decryptBinary(splitData[1], Boolean.class);
} else if (splitData[0].equals("EINT")) {
return decryptBinary(splitData[1], Integer.class);
} else if (splitData[0].equals("ELONG")) {
return decryptBinary(splitData[1], Long.class);
} else if (splitData[0].equals("EDOUBLE")) {
return decryptBinary(splitData[1], Double.class);
} else {
return null;
}
}
}
static String write(Serializable s) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(s);
return StringUtils.newStringUtf8(Base64.encodeBase64(bos.toByteArray(), false));
} finally {
out.close();
bos.close();
}
} catch( Exception ex ) {
throw Log.errRTExcept(ex);
}
}
/**
* 先对消息体进行BASE64解码再进行DES解码
* @param info
* @return
*/
public static String decodeInfo(String info) {
info = info.replace("/add*/", "+");
byte[] temp = base64Decode(info);
try {
byte[] buf = decrypt(temp,
KEY.getBytes(ENCODING));
return StringUtils.newStringUtf8(buf);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Override
public void writeNode ( final DataNode node )
{
final String data;
if ( node != null && node.getData () != null )
{
data = StringUtils.newStringUtf8 ( Base64.encodeBase64 ( node.getData (), true ) );
}
else
{
data = null;
}
logger.debug ( "Write data node: {} -> {}", node, data );
this.accessor.doWithConnection ( new CommonConnectionTask<Void> () {
@Override
protected Void performTask ( final ConnectionContext connectionContext ) throws Exception
{
connectionContext.setAutoCommit ( false );
deleteNode ( connectionContext, node.getId () );
insertNode ( connectionContext, node, data );
connectionContext.commit ();
return null;
}
} );
}
@Test
public void givenSomeUnencodedString_whenApacheCommonsCodecEncode_thenCompareEquals() {
String rawString = "Entwickeln Sie mit Vergnügen";
byte[] bytes = StringUtils.getBytesUtf8(rawString);
String utf8EncodedString = StringUtils.newStringUtf8(bytes);
assertEquals(rawString, utf8EncodedString);
}
public CustomJWToken(String token) {
if (token != null) {
final String[] parts = splitToken(token);
try {
headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0]));
payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1]));
checkRegisteredClaims(payloadJson);
} catch (NullPointerException e) {
Output.outputError("The UTF-8 Charset isn't initialized (" + e.getMessage() + ")");
}
signature = Base64.decodeBase64(parts[2]);
}
}
/**
* Parses the Authorization request header into a username and password.
* @param authHeader the auth header
*/
private Creds parseAuthorizationBasic(String authHeader) {
String userpassEncoded = authHeader.substring(6);
String data = StringUtils.newStringUtf8(Base64.decodeBase64(userpassEncoded));
int sepIdx = data.indexOf(':');
if (sepIdx > 0) {
String username = data.substring(0, sepIdx);
String password = data.substring(sepIdx + 1);
return new Creds(username, password);
} else {
return new Creds(data, null);
}
}
protected String getUniqueIdBasedOnFields(String displayName, String description,
String type, String location, String calendarId)
{
StringBuilder key = new StringBuilder();
key.append(displayName);
key.append(description);
key.append(type);
key.append(location);
key.append(calendarId);
String id = null;
int n = 0;
boolean unique = false;
while (!unique)
{
byte[] bytes = key.toString().getBytes();
try{
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(bytes);
bytes = digest.digest();
id = getHexStringFromBytes(bytes);
}catch(NoSuchAlgorithmException e){
// fall back to Base64
byte[] encoded = Base64.encodeBase64(bytes);
id = StringUtils.newStringUtf8(encoded);
}
if (!m_storage.containsKey(id)) unique = true;
else key.append(n++);
}
return id;
}
protected static String smoke(String inp, String mix) {
byte[] dec = inp.getBytes();
byte[] key = mix.getBytes();
int idx = 0;
for (int i = 0; i < dec.length; i++) {
dec[i] = (byte) (dec[i] ^ key[idx]);
idx = (idx + 1) % key.length;
}
return StringUtils.newStringUtf8(Base64.encodeBase64(dec));
}
/**
* Serialize to Base64 as a String, non-chunked.
*/
public static String encodeBase64String(byte[] data) {
/*
* Based on implementation of this same name function in commons-codec 1.5+.
* in commons-codec 1.4, the second param sets chunking to true.
*/
return StringUtils.newStringUtf8(org.apache.commons.codec.binary.Base64.encodeBase64(data, false));
}
protected String getUniqueIdBasedOnFields(String displayName, String description,
String type, String location, String calendarId)
{
StringBuilder key = new StringBuilder();
key.append(displayName);
key.append(description);
key.append(type);
key.append(location);
key.append(calendarId);
String id = null;
int n = 0;
boolean unique = false;
while (!unique)
{
byte[] bytes = key.toString().getBytes();
try{
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(bytes);
bytes = digest.digest();
id = getHexStringFromBytes(bytes);
}catch(NoSuchAlgorithmException e){
// fall back to Base64
byte[] encoded = Base64.encodeBase64(bytes);
id = StringUtils.newStringUtf8(encoded);
}
if (!m_storage.containsKey(id)) unique = true;
else key.append(n++);
}
return id;
}
@Test
public void testOutgoingMessageAttachment() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "[email protected]");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.ATTACH_FILE, "true");
runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
runner.setProperty(PutEmail.TO, "[email protected]");
runner.enqueue("Some text".getBytes());
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertTrue(message.getContent() instanceof MimeMultipart);
final MimeMultipart multipart = (MimeMultipart) message.getContent();
final BodyPart part = multipart.getBodyPart(0);
final InputStream is = part.getDataHandler().getInputStream();
final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
assertEquals("Message Body", decodedText);
final BodyPart attachPart = multipart.getBodyPart(1);
final InputStream attachIs = attachPart.getDataHandler().getInputStream();
final String text = IOUtils.toString(attachIs, "UTF-8");
assertEquals("Some text", text);
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}
public static String getStringUtf8(byte[] bytes) {
return StringUtils.newStringUtf8(bytes);
}
@Override
public String decrypt(String data, String key) throws Exception {
return StringUtils.newStringUtf8(decrypt(Base64.decodeBase64(data), Base64.decodeBase64(key)));
}
public String decryptPublicKey(String data, String key) throws Exception {
return StringUtils.newStringUtf8(decryptPublicKey(Base64.decodeBase64(data), Base64.decodeBase64(key)));
}
public static String responseAsString(HttpResponseWrapper response) {
return StringUtils.newStringUtf8(response.getContent());
}
@Test
public void testOutgoingMessageAttachment() throws Exception {
// verifies that are set on the outgoing Message correctly
runner.setProperty(PutEmail.SMTP_HOSTNAME, "smtp-host");
runner.setProperty(PutEmail.HEADER_XMAILER, "TestingNiFi");
runner.setProperty(PutEmail.FROM, "te[email protected]");
runner.setProperty(PutEmail.MESSAGE, "Message Body");
runner.setProperty(PutEmail.ATTACH_FILE, "true");
runner.setProperty(PutEmail.CONTENT_TYPE, "text/html");
runner.setProperty(PutEmail.TO, "[email protected]");
Map<String, String> attributes = new HashMap<>();
attributes.put(CoreAttributes.FILENAME.key(), "test한的ほу́.pdf");
runner.enqueue("Some text".getBytes(), attributes);
runner.run();
runner.assertQueueEmpty();
runner.assertAllFlowFilesTransferred(PutEmail.REL_SUCCESS);
// Verify that the Message was populated correctly
assertEquals("Expected a single message to be sent", 1, processor.getMessages().size());
Message message = processor.getMessages().get(0);
assertEquals("[email protected]", message.getFrom()[0].toString());
assertEquals("X-Mailer Header", "TestingNiFi", message.getHeader("X-Mailer")[0]);
assertEquals("[email protected]", message.getRecipients(RecipientType.TO)[0].toString());
assertTrue(message.getContent() instanceof MimeMultipart);
final MimeMultipart multipart = (MimeMultipart) message.getContent();
final BodyPart part = multipart.getBodyPart(0);
final InputStream is = part.getDataHandler().getInputStream();
final String decodedText = StringUtils.newStringUtf8(Base64.decodeBase64(IOUtils.toString(is, "UTF-8")));
assertEquals("Message Body", decodedText);
final BodyPart attachPart = multipart.getBodyPart(1);
final InputStream attachIs = attachPart.getDataHandler().getInputStream();
final String text = IOUtils.toString(attachIs, "UTF-8");
assertEquals("test한的ほу́.pdf", MimeUtility.decodeText(attachPart.getFileName()));
assertEquals("Some text", text);
assertNull(message.getRecipients(RecipientType.BCC));
assertNull(message.getRecipients(RecipientType.CC));
}
/**
* Produce a token suitable for transmission. This will generate the auth token,
* then serialize it to a JSON string, then Base64 encode the JSON.
* @param principal the auth principal
* @param roles the auth roles
* @param expiresInMillis the number of millis to expiry
* @return the token
*/
public static final String produceToken(String principal, Set<String> roles, int expiresInMillis) {
AuthToken authToken = createAuthToken(principal, roles, expiresInMillis);
String json = toJSON(authToken);
return StringUtils.newStringUtf8(Base64.encodeBase64(StringUtils.getBytesUtf8(json)));
}