/src/main/com/mongodb/util/JSONCallback.java

https://github.com/alphaadidas/mongo-java-driver · Java · 103 lines · 90 code · 11 blank · 2 comment · 30 complexity · a043513cd32cc09a1805de40bfcebe7b MD5 · raw file

  1. // JSONCallback.java
  2. package com.mongodb.util;
  3. import java.text.*;
  4. import java.util.*;
  5. import java.util.regex.*;
  6. import org.bson.*;
  7. import org.bson.types.*;
  8. import com.mongodb.*;
  9. public class JSONCallback extends BasicBSONCallback {
  10. @Override
  11. public BSONObject create(){
  12. return new BasicDBObject();
  13. }
  14. @Override
  15. protected BSONObject createList() {
  16. return new BasicDBList();
  17. }
  18. public void objectStart(boolean array, String name){
  19. _lastArray = array;
  20. super.objectStart( array , name );
  21. }
  22. public Object objectDone(){
  23. String name = curName();
  24. Object o = super.objectDone();
  25. BSONObject b = (BSONObject)o;
  26. // override the object if it's a special type
  27. if ( ! _lastArray ) {
  28. if ( b.containsField( "$oid" ) ) {
  29. o = new ObjectId((String)b.get("$oid"));
  30. if (!isStackEmpty()) {
  31. gotObjectId( name, (ObjectId)o);
  32. } else {
  33. setRoot(o);
  34. }
  35. } else if ( b.containsField( "$date" ) ) {
  36. SimpleDateFormat format =
  37. new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  38. format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
  39. o = format.parse((String)b.get("$date"), new ParsePosition(0));
  40. if (!isStackEmpty()) {
  41. cur().put( name, o );
  42. } else {
  43. setRoot(o);
  44. }
  45. } else if ( b.containsField( "$regex" ) ) {
  46. o = Pattern.compile( (String)b.get( "$regex" ),
  47. BSON.regexFlags( (String)b.get( "$options" )) );
  48. if (!isStackEmpty()) {
  49. cur().put( name, o );
  50. } else {
  51. setRoot(o);
  52. }
  53. } else if ( b.containsField( "$ts" ) ) {
  54. Long ts = (Long) b.get("$ts");
  55. Long inc = (Long) b.get("$inc");
  56. o = new BSONTimestamp(ts.intValue(), inc.intValue());
  57. if (!isStackEmpty()) {
  58. cur().put( name, o );
  59. } else {
  60. setRoot(o);
  61. }
  62. } else if ( b.containsField( "$code" ) ) {
  63. if (b.containsField("$scope")) {
  64. o = new CodeWScope((String)b.get("$code"), (DBObject)b.get("$scope"));
  65. } else {
  66. o = new Code((String)b.get("$code"));
  67. }
  68. if (!isStackEmpty()) {
  69. cur().put( name, o );
  70. } else {
  71. setRoot(o);
  72. }
  73. } else if ( b.containsField( "$ref" ) ) {
  74. o = new DBRef(null, (String)b.get("$ref"), b.get("$id"));
  75. if (!isStackEmpty()) {
  76. cur().put( name, o );
  77. } else {
  78. setRoot(o);
  79. }
  80. } else if ( b.containsField( "$uuid" ) ) {
  81. o = UUID.fromString((String)b.get("$uuid"));
  82. if (!isStackEmpty()) {
  83. cur().put( name, o );
  84. } else {
  85. setRoot(o);
  86. }
  87. }
  88. }
  89. return o;
  90. }
  91. private boolean _lastArray = false;
  92. }