Reputation: 9241
Using the Java driver, what's the best way to convert an ObjectID to/from a string with Base64 encoding?
The ObjectIds will be part of a URL so I'd like to shorten them a bit.
Upvotes: 2
Views: 5545
Reputation: 41290
Use the javax.xml.bind.DatatypeConverter which is a part of Java
parseBase64Binary(String lexicalXSDBase64Binary) to convert a base64 into a binary string printHexBinary(byte[] val) to print it out as a hex string.
The advantage of this is you are not adding any additional libraries outside JavaEE5 or Java 6
Upvotes: 0
Reputation: 9241
I looked at the ObjectId source code and none of the internal string-ifying methods help.
Seems that you need to useObjectId.toByteArray()
and ObjectId( byte[])
in conjunction with an external Base64 encoder/decoder. The Java Mongo driver used to have com.mongodb.util.Base64
, but it doesn't seem to be part of the library any longer so I used the Base64 library in Apache Commons.
Here's an example of the conversions using Base64 in Apache Commons:
static public ObjectId toObjectId( String stringId)
{
return new ObjectId( Base64.decodeBase64( stringId));
}
static public String toString( ObjectId objectId)
{
return Base64.encodeBase64URLSafeString( objectId.toByteArray());
}
Upvotes: 2
Reputation: 5548
The ObjectId class does have a toString() method, and a string may be provided in the constructor. However, these strings are base-16 (hexadecimal), and may bot be what you are looking for.
The API information may be found here: http://api.mongodb.org/java/current/
For base 64 encoding, a colleague of mine suggested that it may be preferable to use the toByteArray() method, and convert that to a base 64 string. Going the other way, the ObjectId constructor may be passed a byte array.
A Google search for "java library base64 encoding" reveals another Stack Overflow question that contains more detail on converting byte arrays to base 64 strings and back again.
Decode Base64 data in Java
The above thread contains a link to the base64 class, part of the Apache Commons Codec.
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
Hopefully this will get you where you need to go, or at least give you some additional options to consider.
Upvotes: 3
Reputation: 625
Instead of Base64, you could just use URLEncoder and URLDecoder, which has nothing to do with MongoDB but converts Strings into a valid URL-Strings.
Upvotes: 0