Created
September 22, 2015 09:35
-
-
Save rozza/9c94808ed5b4f1edca75 to your computer and use it in GitHub Desktop.
Example of static helpers to convert to and from InputStreams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import org.bson.BsonBinaryReader; | |
import org.bson.BsonBinaryWriter; | |
import org.bson.Document; | |
import org.bson.codecs.Codec; | |
import org.bson.codecs.DecoderContext; | |
import org.bson.codecs.DocumentCodec; | |
import org.bson.codecs.EncoderContext; | |
import org.bson.io.BasicOutputBuffer; | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.nio.ByteBuffer; | |
import static java.util.Arrays.asList; | |
public class DocumentToBinary { | |
private static Codec<Document> DOCUMENT_CODEC = new DocumentCodec(); | |
public static void main(final String[] args) { | |
Document myDocument = new Document("_id", 1).append("key1", asList(1, 2, 3, 4)); | |
try { | |
Document myCopiedDocument = fromInputStream(toInputStream(myDocument)); | |
assert myCopiedDocument.equals(myDocument); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static InputStream toInputStream(final Document document) { | |
BasicOutputBuffer outputBuffer = new BasicOutputBuffer(); | |
BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer); | |
DOCUMENT_CODEC.encode(writer, document, EncoderContext.builder().isEncodingCollectibleDocument(true).build()); | |
return new ByteArrayInputStream(outputBuffer.toByteArray()); | |
} | |
public static Document fromInputStream(final InputStream input) throws IOException { | |
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); | |
byte[] buffer = new byte[1024]; | |
int len; | |
while ((len = input.read(buffer)) != -1) { | |
outputStream.write(buffer, 0, len); | |
} | |
outputStream.close(); | |
BsonBinaryReader bsonReader = new BsonBinaryReader(ByteBuffer.wrap(outputStream.toByteArray())); | |
return DOCUMENT_CODEC.decode(bsonReader, DecoderContext.builder().build()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment