Exemplo n.º 1
0
  public void showUserline(String username) {
    MongoCollection<Document> users = db.getCollection("users");
    Document oldDoc = users.find(eq("username", username)).first();
    if (oldDoc == null) {
      System.out.println("* Show userline failed : Username does not exist");
    } else {
      MongoCollection<Document> userline = db.getCollection("userline");
      List<Document> userlineList =
          userline.find(eq("username", username)).into(new ArrayList<Document>());
      if (userlineList.isEmpty()) {
        System.out.println("* " + username + "'s userline is empty");
      } else {
        MongoCollection<Document> tweets = db.getCollection("tweets");
        List<Date> timeList = new ArrayList<>();
        List<String> bodyList = new ArrayList<>();
        for (Document doc : userlineList) {
          Date time = (Date) doc.get("time");
          ObjectId tweet_id = (ObjectId) doc.get("tweet_id");
          Document tweetDoc = tweets.find(eq("tweet_id", tweet_id)).first();
          String body = (String) tweetDoc.get("body");

          timeList.add(time);
          bodyList.add(body);
        }

        System.out.println("* @" + username + "'s userline");
        for (int i = 0; i < timeList.size(); i++) {
          System.out.println("[" + timeList.get(i) + "] " + bodyList.get(i));
        }
      }
    }
  }
Exemplo n.º 2
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);
       }
     }
   }
 }
  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);
    }
  }
Exemplo n.º 4
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();
    }
  }
Exemplo n.º 5
0
 /**
  * Retrieved a previously stored scheduled calendar in the database.
  *
  * @param id ID of the user.
  * @param calendarName Name of the calendar to retrieve.
  * @return List of DutyBlocks comprising the calendar retrieved.
  */
 public ArrayList<DutyBlock> getScheduledCalendar(String id, String calendarName) {
   MongoCollection col = db.getCollection("ScheduledCalendars");
   Document testDoc = (Document) col.find(new Document("name", id + calendarName)).first();
   // Access collection of scheduled calendars.
   MongoCollection<ScheduledDuty> collection =
       db.getCollection("ScheduledCalendars").withDocumentClass(ScheduledDuty.class);
   // Search for specified calendar.
   ScheduledDuty doc =
       (ScheduledDuty) collection.find(new Document("name", id + calendarName)).first();
   return doc.getDutyCalendar();
 }
Exemplo n.º 6
0
  public void removeOtherBookingsIfAny(String email, String bookingId) {
    final List<String> extraBookings = new ArrayList<String>();
    try {
      final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
      final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
      final Document findCr = new Document();
      findCr.put(DBConstants.EMAIL, email);
      final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>());

      for (final Document document : lstBkngs) {
        if (!StringUtils.equalsIgnoreCase(bookingId, document.getString(DBConstants.BOOKING_ID))) {
          extraBookings.add(document.getString(DBConstants.BOOKING_ID));
        }
      }

      if (!extraBookings.isEmpty()) {
        QueryBuilder deleteQuery = new QueryBuilder();
        deleteQuery
            .put(DBConstants.BOOKING_ID)
            .in(extraBookings.toArray(new String[extraBookings.size()]));
        coll.deleteMany((Bson) deleteQuery.get());
      }
    } catch (Exception e) {
      e.printStackTrace();
      if (e instanceof com.mongodb.MongoTimeoutException) {
        throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
      }
      throw new ApplicationException(
          MessagesEnum.CLOSE_BOOKING_FAILED.getMessage(extraBookings.toString()), e);
    }
  }
Exemplo n.º 7
0
  @Override
  public List<?> queryPage(MongoCollection<Document> coll, Bson filter, int page, int pageSize) {
    List<Document> list = new ArrayList<Document>();
    coll.find(filter).skip((page - 1) * pageSize).limit(pageSize).into(list);

    return list;
  }
Exemplo n.º 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);
    }
  }
Exemplo n.º 9
0
  public void init() {

    try {
      schedFact = new org.quartz.impl.StdSchedulerFactory();
      sched = schedFact.getScheduler();
      if (sched.isStarted() == false) sched.start();

      MongoCollection<BsonDocument> collection =
          Configuration.mongoDatabase.getCollection("Subscription", BsonDocument.class);

      Iterator<BsonDocument> subIterator = collection.find(BsonDocument.class).iterator();
      MongoQueryService queryService = new MongoQueryService();
      while (subIterator.hasNext()) {
        BsonDocument sub = subIterator.next();
        SubscriptionType subscription = new SubscriptionType(sub);
        if (subscription.getSchedule() != null && subscription.getTrigger() == null) {
          queryService.addScheduleToQuartz(subscription);
        } else if (subscription.getSchedule() == null && subscription.getTrigger() != null) {
          TriggerEngine.addTriggerSubscription(
              sub.getString("subscriptionID").getValue(), subscription);
        }
      }

    } catch (SchedulerException e) {
      Configuration.logger.log(Level.ERROR, e.toString());
    }
  }
Exemplo n.º 10
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); // 没有数据就执行添加操作
    }
  }
Exemplo n.º 11
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);
  }
Exemplo n.º 12
0
  public User getBooking(final String bookingId) {
    /**
     * Creating 'nextUserEmailInQueue' as string buffer because value cannot be reassigned as it is
     * declared as final
     */
    final User user = new User();
    try {
      final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
      final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
      final Document findCr = new Document();
      findCr.put(DBConstants.BOOKING_ID, bookingId);
      final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>());

      for (final Document document : lstBkngs) {
        user.setEmail(document.getString(DBConstants.EMAIL));
        user.setBookingId(document.getString(DBConstants.BOOKING_ID));
      }
    } catch (Exception e) {
      if (e instanceof com.mongodb.MongoTimeoutException) {
        throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
      }
      throw new ApplicationException(MessagesEnum.BOOKINGS_RETRIVAL_FAILED.getMessage(), e);
    }
    return user;
  }
Exemplo n.º 13
0
  @Override
  public List<?> query(MongoCollection<Document> coll, Bson condition, Bson filter) {
    List<Document> list = new ArrayList<Document>();
    coll.find(condition).projection(filter).into(list);

    return list;
  }
Exemplo n.º 14
0
  @Override
  public List<?> query(MongoCollection<Document> coll) {
    List<Document> list = new ArrayList<Document>();
    coll.find().into(list);

    return list;
  }
Exemplo n.º 15
0
  @SuppressWarnings("deprecation")
  public boolean passBooking(User currentUserBooking, User nextUserInQueue) {
    try {
      final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
      final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
      final Document findCr = new Document();
      findCr.put(DBConstants.BOOKING_ID, nextUserInQueue.getBookingId());
      final ArrayList<Document> lstBkngs = coll.find(findCr).into(new ArrayList<Document>());

      for (final Document document : lstBkngs) {
        java.util.Date nextUserBookingTime = document.getDate(DBConstants.BOOKED_DATE_N_TIME);
        nextUserBookingTime.setSeconds(nextUserBookingTime.getSeconds() + 1);
        currentUserBooking.setBookedDateNTime(nextUserBookingTime);
      }

      // update current user booking time
      final Document filterQuery = new Document();
      filterQuery.put(DBConstants.BOOKING_ID, currentUserBooking.getBookingId());
      final Document updateQuery = new Document();
      final Document updateSet = new Document();
      updateSet.put(DBConstants.BOOKED_DATE_N_TIME, currentUserBooking.getBookedDateNTime());
      updateQuery.put("$set", updateSet);
      coll.updateOne(filterQuery, updateQuery);
    } catch (Exception e) {
      if (e instanceof com.mongodb.MongoTimeoutException) {
        throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
      }
      throw new ApplicationException(MessagesEnum.PASSING_BOOKING_FAILED.getMessage(), e);
    }
    return true;
  }
Exemplo n.º 16
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);
  }
Exemplo n.º 17
0
  public void removeInheritance(Group group) {
    inherits.remove(group.getName());

    MongoCollection<Document> collection = MongoConnection.getCollection("perms", "groups");
    Document doc = collection.find(eq("group", name)).first();
    doc.put("inherits", inherits);
    collection.replaceOne(eq("group", name), doc);
  }
Exemplo n.º 18
0
  public static List<String> queryMongoForSimilar(String courtId, String facets) throws Exception {
    // Query mongo for other facets with these values.
    System.out.println("Court id is: " + courtId);
    initializeMap();
    List<String> facetList = facetStringToListOfKeys(facets);
    // Facet list has the keys to get. Query mongo for the document with given courtId, then pull
    // the values of these keys.

    MongoConnection mc = new MongoConnection("supremeCourtDataDB.properties");
    MongoCollection<Document> collection = mc.getCollection();

    int courtIdInt = Integer.parseInt(courtId);
    Document d = collection.find(eq("courtId", courtIdInt)).first();
    System.out.println("Doc with this court id: " + d);

    Document queryDoc = new Document();
    // Build query based on given keys and their values in this doc.
    for (int i = 0; i < facetList.size(); i++) {
      String key = facetList.get(i);
      String tempString;
      int tempInt;
      try {
        tempString = d.getString(key);
        // queryJSON.put(key, tempString);
        queryDoc.put(key, tempString);
      } catch (ClassCastException c) {
        tempInt = d.getInteger(key);
        queryDoc.put(key, tempInt);
        // queryJSON.put(key, tempInt);
      }
    }

    List<String> resultList = new ArrayList<String>();

    System.out.println("Querying mongo.");
    FindIterable<Document> result = collection.find(queryDoc);

    for (Document doc : result) {
      String temp = Integer.toString(doc.getInteger("courtId"));
      resultList.add(temp);
    }

    System.out.println("Done!");
    return resultList;
  }
Exemplo n.º 19
0
 public String getSharedAccounts() {
   String playerUUID = slp.getUniqueId().toString();
   Set<String> sharedUUIDs = new HashSet<>();
   Collection<String> ips = new HashSet<>();
   MongoCollection<Document> col =
       SpleefLeague.getInstance().getPluginDB().getCollection("PlayerConnections");
   Date lastOnline = null;
   for (Document doc : col.find(new Document("uuid", playerUUID))) {
     ips.add(doc.get("ip", String.class));
     if (lastOnline == null) {
       lastOnline = doc.get("date", Date.class);
     } else {
       Date d = doc.get("date", Date.class);
       if (lastOnline.before(d)) {
         lastOnline = d;
       }
     }
   }
   lastSeen = lastOnline != null ? TimeUtil.dateToString(lastOnline, false) + " ago" : "Unknown";
   Set<Document> orQuerry = new HashSet<>();
   for (String ip : ips) {
     orQuerry.add(new Document("ip", ip));
     Thread.currentThread().getStackTrace();
   }
   if (!orQuerry.isEmpty()) {
     for (Document doc : col.find(new Document("$or", orQuerry))) {
       String uuid = doc.get("uuid", String.class);
       if (!uuid.equals(playerUUID)) {
         sharedUUIDs.add(uuid);
       }
     }
   }
   col = SpleefLeague.getInstance().getPluginDB().getCollection("Players");
   String sharedUsernames = null;
   for (String uuid : sharedUUIDs) {
     if (sharedUsernames == null) {
       sharedUsernames =
           col.find(new Document("uuid", uuid)).first().get("username", String.class);
     } else {
       sharedUsernames +=
           ", " + col.find(new Document("uuid", uuid)).first().get("username", String.class);
     }
   }
   return sharedUsernames;
 }
Exemplo n.º 20
0
 public List<Document> findByDateDescending(int limit) {
   List<Document> posts =
       postsCollection
           .find()
           .limit(limit)
           .sort(new BasicDBObject("date", -1))
           .into(new ArrayList<Document>());
   return posts;
 }
Exemplo n.º 21
0
 @Override
 public Document findOneAndDelete(Bson arg0, FindOneAndDeleteOptions arg1) {
   if (tx.started()) {
     tx.deleteOne(coll, arg0);
     return coll.find(arg0).first();
   } else {
     return coll.findOneAndDelete(arg0, arg1);
   }
 }
 /** {@inheritDoc} */
 @Override
 public Map<String, Feature> readAll() {
   LinkedHashMap<String, Feature> mapFP = new LinkedHashMap<String, Feature>();
   for (Document document : collection.find()) {
     Feature feature = MAPPER.mapFeature(document);
     mapFP.put(feature.getUid(), feature);
   }
   return mapFP;
 }
Exemplo n.º 23
0
    @Override
    public boolean start() {
      Read spec = source.spec;
      client = new MongoClient(new MongoClientURI(spec.uri()));

      MongoDatabase mongoDatabase = client.getDatabase(spec.database());

      MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(spec.collection());

      if (spec.filter() == null) {
        cursor = mongoCollection.find().iterator();
      } else {
        Document bson = Document.parse(spec.filter());
        cursor = mongoCollection.find(bson).iterator();
      }

      return advance();
    }
 /** {@inheritDoc} */
 @Override
 public Set<String> readAllGroups() {
   Set<String> setOfGroups = new HashSet<String>();
   for (Document document : collection.find()) {
     setOfGroups.add(document.getString(GROUPNAME));
   }
   setOfGroups.remove(null);
   setOfGroups.remove("");
   return setOfGroups;
 }
Exemplo n.º 25
0
  public Document findByPermalink(String permalink) {
    Document post = postsCollection.find(eq("permalink", permalink)).first();

    if (post == null) {
      System.out.println("post not found");
      return null;
    }

    return post;
  }
 /** {@inheritDoc} */
 @Override
 public Feature read(String uid) {
   if (uid == null || uid.isEmpty()) {
     throw new IllegalArgumentException("Feature identifier cannot be null nor empty");
   }
   Document object = collection.find(BUILDER.getFeatUid(uid)).first();
   if (object == null) {
     throw new FeatureNotFoundException(uid);
   }
   return MAPPER.mapFeature(object);
 }
Exemplo n.º 27
0
  @Path("/clientObjects")
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response sendObservecCancel() throws Exception {

    MongoCollection<Document> document = MongoConnection.getServerSideCLientObject();
    List<Document> foundDocument = document.find().into(new ArrayList<Document>());
    JSONArray jsonArray = new JSONArray(foundDocument);

    return Response.status(200).entity(jsonArray.toString()).build();
  }
Exemplo n.º 28
0
  public User getUser(String username) {
    Document query = new Document(Config.USER_USERNAME, username.toLowerCase());

    MongoCursor<Document> cursor = userCollection.find(query).iterator();
    if (!cursor.hasNext()) {
      throw new IllegalArgumentException("Username " + username + " not found in user collection");
    }

    Document userDocument = cursor.next();

    return new User(userDocument);
  }
Exemplo n.º 29
0
 public RecipeSummary getRecipeSummary(String recipeId) {
   MongoCollection<BsonDocument> collectionRecipeSummary =
       database.getCollection("recipeSummary", BsonDocument.class);
   BsonDocument document = collectionRecipeSummary.find(eq("_id", recipeId)).first();
   if (document != null) {
     LOG.info("get document = {}", document.toString());
     return new RecipeSummary().fromJson(document.toJson());
   } else {
     LOG.info("Null Document for recipeId={}", recipeId);
     return null;
   }
 }
Exemplo n.º 30
0
 /**
  * This method tries to load an solution from the database
  *
  * @since 27.11.15
  * @param enigmaString string of the puzzle
  * @return {@link Solution}
  */
 public static Solution getSolution(final String enigmaString) {
   MongoDatabase lettersdb = mongoClient.getDatabase(databaseName);
   MongoCollection<Document> collection = lettersdb.getCollection(solutionCollectionName);
   Document searchDocument = new Document("string", enigmaString);
   Document document = collection.find(searchDocument).first();
   Solution solution = null;
   if (document != null) {
     solution = new Solution(document);
   } else {
     System.out.println("Keine Lösung in Datenbank");
   }
   return solution;
 }