예제 #1
0
  public void saveOrUpdate(Document widgetDoc) {
    logger.debug("--> to be save widget -->");
    String tableName = "Widget";
    MongoDatabase db = mongoClient.getDatabase(widgetDoc.getString("appId"));
    MongoCollection<Document> collection = db.getCollection(tableName);

    if (!widgetDoc.containsKey("_id")) {
      ObjectId objId = new ObjectId();
      widgetDoc.put("_id", objId);
      logger.debug("--> to insert " + tableName + " with " + widgetDoc.toJson());
      collection.insertOne(widgetDoc); // 没有数据就执行添加操作
      return;
    }

    String objectId = widgetDoc.get("_id").toString();
    Document matchFields = new Document();
    matchFields.put("_id", new ObjectId(objectId));
    if (collection.find(matchFields).iterator().hasNext()) { // 有数据就执行更新操作
      logger.debug("--> to update " + tableName + " with " + widgetDoc.toJson());
      collection.updateOne(matchFields, new Document("$set", widgetDoc));
    } else {
      logger.debug("--> to save " + tableName + " with " + widgetDoc.toJson());
      collection.insertOne(widgetDoc); // 没有数据就执行添加操作
    }
  }
예제 #2
0
  public void tweet(String body) {
    final ObjectId tweet_id = new ObjectId();
    final Date time = new Date();
    MongoCollection<Document> tweets = db.getCollection("tweets");
    MongoCollection<Document> userline = db.getCollection("userline");
    MongoCollection<Document> timeline = db.getCollection("timeline");
    MongoCollection<Document> followers = db.getCollection("followers");

    Document tweetDoc =
        new Document("tweet_id", tweet_id).append("username", nick).append("body", body);

    Document userDoc =
        new Document("username", nick).append("time", time).append("tweet_id", tweet_id);

    List<Document> timelineList = new ArrayList<>();
    List<Document> followerList =
        followers.find(eq("username", nick)).into(new ArrayList<Document>());
    for (Document doc : followerList) {
      String follower = (String) doc.get("follower");
      Document timeDoc =
          new Document("username", follower).append("time", time).append("tweet_id", tweet_id);
      timelineList.add(timeDoc);
    }

    tweets.insertOne(tweetDoc);
    userline.insertOne(userDoc);
    timeline.insertMany(timelineList);

    System.out.println("* You tweeted \"" + body + "\" at " + time);
  }
예제 #3
0
 public void follow(String followed) {
   if (followed.equals(nick)) {
     System.out.println("* Follow failed : You cannot follow yourself");
   } else {
     MongoCollection<Document> users = db.getCollection("users");
     Document oldDoc = users.find(eq("username", followed)).first();
     if (oldDoc == null) {
       System.out.println("* Follow failed : Username does not exist");
     } else {
       MongoCollection<Document> friends = db.getCollection("friends");
       Document frDoc = friends.find(and(eq("username", nick), eq("friend", followed))).first();
       if (frDoc != null) {
         System.out.println("* Follow failed : You already followed @" + followed);
       } else {
         MongoCollection<Document> followers = db.getCollection("followers");
         Date ts = new Date();
         Document friendDoc =
             new Document("username", nick).append("friend", followed).append("since", ts);
         Document followerDoc =
             new Document("username", followed).append("follower", nick).append("since", ts);
         friends.insertOne(friendDoc);
         followers.insertOne(followerDoc);
         System.out.println("* You successfully followed " + followed);
       }
     }
   }
 }
예제 #4
0
  private static void doSomething(MongoClient mongo) {
    MongoDatabase db = mongo.getDatabase("testdb");

    MongoCollection<Document> collection = db.getCollection("users");

    Document user = new Document("username", "johnd");
    user.append("_id", 1);
    user.append("firstName", "John");
    user.append("name", "Doe");
    user.append("enabled", Boolean.FALSE);
    user.append("noOfLogins", 0);
    user.append("lastLogin", new Date());
    user.append("groups", Arrays.asList("admin", "user"));

    System.out.println(user);
    collection.insertOne(user);

    user = new Document("username", "francol");
    user.append("firstName", "Franco");
    user.append("name", "Lawrence");
    user.append("enabled", Boolean.TRUE);
    user.append("noOfLogins", 0);
    user.append("lastLogin", new Date());
    user.append("groups", Arrays.asList("user"));
    collection.insertOne(user);
  }
예제 #5
0
  // validates that username is unique and insert into db
  public boolean addUser(String username, String password, String email) {

    String passwordHash = makePasswordHash(password, Integer.toString(random.nextInt()));

    // XXX WORK HERE
    // create an object suitable for insertion into the user collection
    // be sure to add username and hashed password to the document. problem instructions
    // will tell you the schema that the documents must follow.
    password = makePasswordHash(password, "asd");
    Document user = new Document("_id", username).append("password", password);

    if (email != null && !email.equals("")) {
      // XXX WORK HERE
      // if there is an email address specified, add it to the document too.
      user.append("email", email);
    }

    try {
      // XXX WORK HERE
      // insert the document into the user collection here
      usersCollection.insertOne(user);
      return true;
    } catch (MongoWriteException e) {
      if (e.getError().getCategory().equals(ErrorCategory.DUPLICATE_KEY)) {
        System.out.println("Username already in use: " + username);
        return false;
      }
      throw e;
    }
  }
 public void updateDeviceLog(String productId, String[] vids, Modal model) {
   MongoCollection<Document> deviceLog = getDeviceLog();
   Document filter = new Document("product-id", productId);
   Document doc = getDeviceLog().find(filter).first();
   if (doc != null && model != null) {
     List<Document> models = doc.get("models", List.class);
     Document m = convertModel(vids, model);
     if (models != null) {
       models.add(m);
     } else {
       models = new ArrayList<>();
       models.add(m);
     }
     doc.append("models", models);
     deviceLog.replaceOne(filter, doc);
   } else {
     Device device = new Device();
     device.setProductId(productId);
     doc = toDocument(device);
     List<Document> models = new ArrayList<>();
     models.add(convertModel(vids, model));
     doc.append("models", models);
     deviceLog.insertOne(doc);
   }
 }
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");
    MongoCollection<Document> collection = db.getCollection("deleteTest");

    collection.drop();

    for (int idx = 1; idx <= 8; idx++) {
      collection.insertOne(new Document("_id", idx));
    }

    System.out.println("Before any deletes");
    List<Document> docs = collection.find().into(new ArrayList<Document>());
    for (Document doc : docs) {
      Helper.prettyPrintJSON(doc);
    }

    // delete 2,3,4

    collection.deleteMany(and(gte("_id", 2), lt("_id", 5)));
    System.out.println("removed gte2 lt5");
    docs = collection.find().into(new ArrayList<Document>());
    for (Document doc : docs) {
      Helper.prettyPrintJSON(doc);
    }

    collection.deleteOne(eq("_id", 8));
    System.out.println("Removed id 8");

    docs = collection.find().into(new ArrayList<Document>());
    for (Document doc : docs) {
      Helper.prettyPrintJSON(doc);
    }
  }
예제 #8
0
  @Test
  public void main() {
    DBConnection.getInstance().getConnection();
    MongoCollection<UserDAO> mongoCollection =
        DBConnection.getInstance().getConnection().getCollection("users", UserDAO.class);

    UserDAO userInfo =
        new UserDAOBuilder()
            .setFirstName("Nazmul")
            .setLastName("Hasan")
            .setFatherName("myfather")
            .setMotherName("mymother")
            .setPhoto("1.jpg")
            .setPhone("myphoone")
            .setEmail("*****@*****.**")
            .setBloodGroup("myblood")
            .setCurrentAddress("mycurrentaddress")
            .setPermanentAddress("mypermanentaddress")
            .build();
    mongoCollection.insertOne(userInfo);

    MongoCursor userProfiles = mongoCollection.find().iterator();
    while (userProfiles.hasNext()) {
      UserDAO dbUserInfo = (UserDAO) userProfiles.next();
      System.out.println(dbUserInfo);
    }
  }
예제 #9
0
  private static void insertTest1(Document obj) {
    MongoClient client = new MongoClient("127.0.0.1", 27017);
    MongoDatabase db = client.getDatabase("test");
    MongoCollection<Document> collection = db.getCollection("Test_table1");

    collection.insertOne(obj);
    client.close();
  }
예제 #10
0
  public static void main(String[] args) throws ParseException {
    System.out.println("coucou");

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("testboss");
    MongoCollection<Document> collection = database.getCollection("restaurants");

    String restaurantId = "41704620";
    MongoCursor<Document> cursor =
        collection
            .find(eq("restaurant_id", restaurantId))
            .projection(fields(include("restaurant_id"), excludeId()))
            .iterator();
    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
      }
    } finally {
      cursor.close();
    }

    System.out.println("fin");

    collection.insertOne(
        new Document(
                "address",
                new Document()
                    .append("street", "2 Avenue")
                    .append("zipcode", "10075")
                    .append("building", "1480")
                    .append("coord", asList(-73.9557413, 40.7720266)))
            .append("borough", "Manhattan")
            .append("cuisine", "Italian")
            .append(
                "grades",
                asList(
                    new Document()
                        .append("date", format.parse("2014-10-01T00:00:00Z"))
                        .append("grade", "A")
                        .append("score", 11),
                    new Document()
                        .append("date", format.parse("2014-01-16T00:00:00Z"))
                        .append("grade", "B")
                        .append("score", 17)))
            .append("name", "Vella")
            .append("restaurant_id", restaurantId));

    cursor = collection.find().iterator();
    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
      }
    } finally {
      cursor.close();
    }
  }
예제 #11
0
 /**
  * Stores a scheduled calendar in the database.
  *
  * @param id ID of the user (unique to the user).
  * @param calendarName Name of the calendar to be stored (unique to calendars owned by the user).
  * @param cal List DutyBlocks comprising the calendar to be stored.
  */
 public void storeScheduledCalendar(String id, String calendarName, ArrayList<DutyBlock> cal) {
   // Access collection of scheduled calendars.
   MongoCollection<ScheduledDuty> collection =
       db.getCollection("ScheduledCalendars", ScheduledDuty.class);
   // Query parameter is uuid + calendarName.
   ScheduledDuty toInsert = new ScheduledDuty(id + calendarName, cal);
   // Insert doc to collection.
   collection.insertOne(toInsert);
 }
예제 #12
0
 /**
  * Stores the score of a prefix in the mongo database.
  *
  * @param prefix the prefix to store
  * @param wordLength the length of the whole word
  * @param score the score of the prefix
  */
 public static void storePrefix(final String prefix, final int wordLength, final double score) {
   MongoDatabase lettersdb = mongoClient.getDatabase(databaseName);
   String prefixCollectionName = createPrefixCollectionName(prefix, wordLength);
   MongoCollection<Document> collection = lettersdb.getCollection(prefixCollectionName);
   Document document = new Document();
   document.put(scoreAttribute, score);
   document.put(prefixAttribute, prefix);
   collection.insertOne(document);
 }
예제 #13
0
  public void init(MongoCollection<Document> meepCol) {
    BlockingQueue<String> queue = new LinkedBlockingQueue<>(10000);
    StatusesSampleEndpoint endpoint = new StatusesSampleEndpoint();
    endpoint.stallWarnings(false);
    Authentication auth =
        new OAuth1(
            "FKzFwHjE3o1wb2pFqH0mr6cRJ",
            "xJ1TsuXwcNmoy8badgqx56DrLFeozx5vwjvQ3kBPtP006cEJtU",
            "3792449836-BYKKiZTnemmCFtvZoo5kwOCrhbB5bKRLIEDtQYs",
            "m4eE9BUvxprUnc7NmfgdxdaYVExha0NmwzW4vGoy7REiM");

    StatusesFilterEndpoint endpoint3 = new StatusesFilterEndpoint();
    endpoint3.locations(
        Lists.newArrayList(
            new Location(
                new Location.Coordinate(-122.356798, 37.213402),
                new Location.Coordinate(-121.9, 38.139441))));

    BasicClient client =
        new ClientBuilder()
            .name("sampleExampleClient")
            .hosts(Constants.STREAM_HOST)
            .endpoint(endpoint3)
            .authentication(auth)
            .processor(new StringDelimitedProcessor(queue))
            .build();
    client.connect();

    JsonParser parser = new JsonParser();
    int validParsedMeeps;
    for (validParsedMeeps = 0; validParsedMeeps < 100; ) {
      if (client.isDone()) {
        System.out.println(
            "Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
        break;
      }

      String msg = null;
      try {
        msg = queue.poll(10, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      if (msg == null) {
        System.out.println("Did not receive a message in 10 seconds");
      } else {
        JsonObject aux = parser.parse(msg).getAsJsonObject();
        Document meep = meepDocumentBuilder(aux, meepCol);
        if (meep != null) {
          validParsedMeeps++;
          meepCol.insertOne(meep);
        }
      }
    }
    client.stop();
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());
  }
예제 #14
0
 @Override
 public void insertOne(Document arg0) {
   if (tx.started()) {
     tx.beforeInsertOne(coll, arg0);
     tx.getTxCollection().insertOne(arg0);
   } else {
     coll.insertOne(arg0);
   }
 }
 /** {@inheritDoc} */
 @Override
 public void create(Feature fp) {
   if (fp == null) {
     throw new IllegalArgumentException("Feature cannot be null nor empty");
   }
   if (exist(fp.getUid())) {
     throw new FeatureAlreadyExistException(fp.getUid());
   }
   collection.insertOne(MAPPER.toDocument(fp));
 }
  public String create() {
    MongoCollection<Document> commentCollection = mongoDatabase.getCollection("posts");

    Document document = new Document();
    document.put("comments", new ArrayList<Document>());
    commentCollection.insertOne(document);

    String generatedId = document.getObjectId("_id").toHexString();

    return generatedId;
  }
예제 #17
0
 public boolean signup(String username, String password) {
   MongoCollection<Document> users = db.getCollection("users");
   Document oldDoc = users.find(eq("username", username)).first();
   if (oldDoc != null) {
     System.out.println("* Signup failed : Username already exists");
     return false;
   } else {
     Document doc = new Document("username", username).append("password", password);
     users.insertOne(doc);
     System.out.println("* User @" + username + " is succesfully signed up");
     // autologin
     nick = username;
     System.out.println("* Welcome to MongoTwitter, @" + username + "!");
     return true;
   }
 }
예제 #18
0
  public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    MongoDatabase mongoDatabase = client.getDatabase("course");
    MongoCollection<Document> collection = mongoDatabase.getCollection("findTest");

    collection.drop();

    // insert 10 documents with a random integer as the value of field "x"
    for (int i = 0; i < 10; i++) {
      collection.insertOne(new Document("x", new Random().nextInt(100)));
    }

    System.out.println("Find one:");
    Document one = collection.find().first();
    System.out.println(one);

    System.out.println("\nFind all: ");
    List<Document> all = collection.find().into(new ArrayList<Document>());
    System.out.println(all);

    System.out.println("\nFind all cursor: ");
    MongoCursor<Document> cursor = collection.find().iterator();
    try {

      while (cursor.hasNext()) {
        System.out.println(cursor.next());
      }

    } finally {
      cursor.close();
    }

    //        System.out.println("\nFind all: ");
    //        DBCursor cursor = collection.find();
    //        try {
    //          while (cursor.hasNext()) {
    //              DBObject cur = cursor.next();
    //              System.out.println(cur);
    //          }
    //        } finally {
    //            cursor.close();
    //        }
    //
    System.out.println("\nCount:");
    long count = collection.count();
    System.out.println(count);
  }
  /**
   * Create a directory
   *
   * @param u The owner
   * @param path The path
   * @param name The name
   * @return The newly created directory
   */
  public static Directory createDirectory(User u, Directory parent, String name) {

    MongoCollection<Document> collection = DataBase.getInstance().getCollection("directories");
    Document newDir = new Document();
    Date now = new Date();

    newDir.put("owner", new ObjectId(u.UID));
    newDir.put("name", name);
    newDir.put("path", parent.name != null ? parent.path + parent.name + "/" : "/");
    newDir.put("creation", now);
    newDir.put("edit", now);
    newDir.put("parent", parent.UID != null ? new ObjectId(parent.UID) : null);

    collection.insertOne(newDir);
    updateDirectoryDate(u, parent);

    return new Directory(newDir);
  }
예제 #20
0
 public void whatsNewsIsRead(String hostname) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_WHATSNEW);
     final Document document = new Document();
     document.put(DBConstants.HOST_NAME, hostname);
     document.put(DBConstants.READ, "Y");
     coll.insertOne(document);
   } catch (MongoWriteException e) {
     if (e.getCode() == 11000) {
       throw new ApplicationException(e);
     }
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(e);
   }
 }
예제 #21
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("course");
    MongoCollection<Document> collection = database.getCollection("deleteTest");

    collection.drop();

    // insert 8 documents, with _id set to the value of the loop variable
    for (int i = 0; i < 8; i++) {
      collection.insertOne(new Document().append("_id", i));
    }

    //        collection.deleteMany(gt("_id", 4));

    collection.deleteOne(eq("_id", 4));

    for (Document cur : collection.find().into(new ArrayList<Document>())) {
      Helpers.printJson(cur);
    }
  }
예제 #22
0
  public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");

    MongoCollection<Document> coll = db.getCollection("findWithSortTest");

    coll.drop();

    for (int i = 0; i < 8; i++) {
      coll.insertOne(new Document().append("_id", i));
    }

    // coll.deleteMany(Filters.gt("_id", 4));
    coll.deleteOne(Filters.eq("_id", 4));

    for (Document cur : coll.find().into(new ArrayList<Document>())) {
      System.out.println(cur);
    }
  }
예제 #23
0
 public boolean addUser(final Map<String, String> userInfo) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_USERS);
     final Document user = new Document();
     user.putAll(userInfo);
     coll.insertOne(user);
   } catch (MongoWriteException e) {
     if (e.getCode() == 11000) {
       throw new ApplicationException(
           MessagesEnum.DUPLICATE_USER.getMessage(userInfo.get(DBConstants.EMAIL)), e);
     }
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(MessagesEnum.ADD_USER_FAILED.getMessage(), e);
   }
   return true;
 }
 @Override
 public int create(SensorTypeInfo sensor) {
   MongoCollection<Document> collection = CloudMongoDB.getInstance().getCollection("Drivers");
   List<Document> values = new LinkedList<>();
   for (MeasureValue sen : sensor.getValues()) {
     Map<String, Object> map = new HashMap<>();
     map.put("name", sen.getName());
     map.put("unit", sen.getUnit());
     Document document = new Document(map);
     values.add(document);
   }
   Map<String, Object> map = new HashMap<>();
   map.put("type", sensor.getType());
   map.put("type_name", sensor.getTypeName());
   map.put("driver_name", sensor.getDriverName());
   map.put("values", values);
   Document doc = new Document(map);
   collection.insertOne(doc);
   return 0;
 }
예제 #25
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");
    MongoCollection<Document> coll = db.getCollection("findWithFilterTest");
    coll.drop();

    for (int i = 0; i < 8; i++) {
      coll.insertOne(new Document().append("_id", i).append("x", i));
    }

    // coll.replaceOne(eq("x", 5),  new Document("_id", 5).append("x", 20).append("update", true));
    // coll.updateOne(eq("_id", 9), new Document("$set", new Document("x", 20)));
    // coll.updateOne(eq("_id", 9), new Document("$set", new Document("x", 20)), new
    // UpdateOptions().upsert(false));
    coll.updateMany(gte("_id", 5), new Document("$inc", new Document("x", 1)));

    List<Document> all = coll.find().into(new ArrayList<Document>());
    for (Document cur : all) {
      printJson(cur);
    }
  }
예제 #26
0
  public String addPost(String title, String body, List tags, String username) {

    System.out.println("inserting blog entry " + title + " " + body);

    String permalink = title.replaceAll("\\s", "_"); // whitespace becomes _
    permalink = permalink.replaceAll("\\W", ""); // get rid of non alphanumeric
    permalink = permalink.toLowerCase();
    permalink = permalink + (new Date()).getTime();

    Document post = new Document();

    if (username != null && !username.equals("")) {
      post.append("author", username);
    }
    if (title != null && !title.equals("")) {
      post.append("title", title);
    }
    if (body != null && !body.equals("")) {
      post.append("body", body);
    }
    if (permalink != null && !permalink.equals("")) {
      post.append("permalink", permalink);
    }
    if (tags != null && !tags.equals("")) {
      post.append("tags", tags);
    }
    post.append("comments", new ArrayList<String>());
    post.append("date", new Date());

    try {
      postsCollection.insertOne(post);
      return permalink;
    } catch (MongoWriteException e) {
      if (e.getError().getCategory().equals(ErrorCategory.UNCATEGORIZED)) {
        System.out.println("Username already in use: " + username);
        return e.getMessage();
      }
      throw e;
    }
  }
예제 #27
0
 public boolean saveBooking(final Map<String, Object> bookingInfo) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
     final Document booking = new Document();
     booking.putAll(bookingInfo);
     coll.insertOne(booking);
   } catch (MongoWriteException e) {
     if (e.getCode() == 11000) {
       throw new ApplicationException(
           MessagesEnum.BOOKINGS_ALREADY_EXISTS.getMessage(
               bookingInfo.get(DBConstants.BOX_NAME), bookingInfo.get(DBConstants.EMAIL)),
           e);
     }
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(MessagesEnum.BOOKING_FAILED.getMessage(), e);
   }
   return true;
 }
예제 #28
0
  // starts a new session in the sessions table
  public String startSession(String username) {

    // get 32 byte random number. that's a lot of bits.
    SecureRandom generator = new SecureRandom();
    byte randomBytes[] = new byte[32];
    generator.nextBytes(randomBytes);

    BASE64Encoder encoder = new BASE64Encoder();

    String sessionID = encoder.encode(randomBytes);

    // build the BSON object
    Document session = new Document("username", username);

    session.append("_id", sessionID);

    sessionsCollection.deleteMany(new Document("username", username));

    sessionsCollection.insertOne(session);

    return session.getString("_id");
  }
예제 #29
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");
    MongoCollection<Document> coll = db.getCollection("findTest");
    coll.drop();

    for (int i = 0; i < 10; i++) {
      coll.insertOne(new Document("x", i));
    }

    System.out.println("Find one:");
    Document first = coll.find().first();
    printJson(first);

    System.out.println("Find all with into:");
    List<Document> all = coll.find().into(new ArrayList<Document>());
    for (Document cur : all) {
      printJson(cur);
    }

    System.out.println("Find all with iteration:");
    MongoCursor<Document> cursor = coll.find().iterator();
    try {
      while (cursor.hasNext()) {
        Document cur = cursor.next();
        printJson(cur);
      }

    } finally {
      // если выбросится исключение
      // так есть надежда, что поиск открытый на сервере закроется
      cursor.close();
    }

    System.out.println("Count:");
    long count = coll.count();
    System.out.println(count);
  }
  public static void main(String[] args) {

    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldMongodbSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient();

    MongoDatabase db = client.getDatabase("course");

    final MongoCollection<Document> coll = db.getCollection("hello");

    coll.drop();

    coll.insertOne(new Document("name", "Mongodb"));

    Spark.get(
        new Route("/") {

          @Override
          public Object handle(Request arg0, Response arg1) {
            StringWriter writer = new StringWriter();
            try {
              Template helloTemplate = configuration.getTemplate("hello.ftl");

              Document document = coll.find().first();

              helloTemplate.process(document, writer);

              // System.out.println(writer);

            } catch (Exception e) {
              halt(500);
              e.printStackTrace();
            }
            return writer;
          }
        });
  }