Java Code Examples for org.apache.commons.codec.binary.StringUtils#newStringUtf8()

The following examples show how to use org.apache.commons.codec.binary.StringUtils#newStringUtf8() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VM.java    From h2o-2 with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 2
Source File: KafkaProduceOffsetFetcher.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    });
}
 
Example 3
Source File: KafkaProduceOffsetFetcher.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    });
}
 
Example 4
Source File: AesCipher.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@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;
        }
    }
}
 
Example 5
Source File: AuthenticationFilter.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: BaseExternalCalendarSubscriptionService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: Base64.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 8
Source File: Traits.java    From raccoon4 with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 9
Source File: BaseExternalCalendarSubscriptionService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: CustomJWToken.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
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]);
	}
}
 
Example 11
Source File: StringEncodeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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);
}
 
Example 12
Source File: JdbcStorageDaoBase64Impl.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@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;
        }
    } );

}
 
Example 13
Source File: DESBase64Util.java    From youqu_master with Apache License 2.0 5 votes vote down vote up
/**
 * 先对消息体进行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 "";
}
 
Example 14
Source File: CodecUtils.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public String decrypt(String data, String key) throws Exception {
    return StringUtils.newStringUtf8(decrypt(Base64.decodeBase64(data), Base64.decodeBase64(key)));
}
 
Example 15
Source File: CodecUtils.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
public String decryptPublicKey(String data, String key) throws Exception {
    return StringUtils.newStringUtf8(decryptPublicKey(Base64.decodeBase64(data), Base64.decodeBase64(key)));
}
 
Example 16
Source File: StringUtility.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String responseAsString(HttpResponseWrapper response) {
    return StringUtils.newStringUtf8(response.getContent());
}
 
Example 17
Source File: AtlasNotificationBaseMessage.java    From atlas with Apache License 2.0 4 votes vote down vote up
public static String getStringUtf8(byte[] bytes) {
    return StringUtils.newStringUtf8(bytes);
}
 
Example 18
Source File: TestPutEmail.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@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));
}
 
Example 19
Source File: TestPutEmail.java    From nifi with Apache License 2.0 4 votes vote down vote up
@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]");

    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));
}
 
Example 20
Source File: AuthTokenUtil.java    From apiman with Apache License 2.0 2 votes vote down vote up
/**
 * 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)));
}