Пример #1
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());
    }
  }
Пример #2
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); // 没有数据就执行添加操作
    }
  }
Пример #3
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("week5");
    MongoCollection<Document> col = db.getCollection("grads");

    Document unwind = new Document("$unwind", "$scores");
    Document quizFilter =
        new Document(
            "$match",
            new Document(
                "$or",
                asList(
                    new Document("scores.type", "exam"), new Document("scores.type", "homework"))));
    Document groupByClassAndStudent =
        new Document(
            "$group",
            new Document()
                .append(
                    "_id",
                    new Document().append("class", "$class_id").append("student", "$student_id"))
                .append("avg_per_student", new Document("$avg", "$scores.score")));
    Document groupByClass =
        new Document(
            "$group",
            new Document()
                .append("_id", "$_id.class")
                .append("avg_per_class", new Document("$avg", "$avg_per_student")));
    Document sort = new Document("$sort", new Document("avg_per_class", 1));

    MongoCursor<Document> cursor =
        col.aggregate(asList(unwind, quizFilter, groupByClassAndStudent, groupByClass, sort))
            .iterator();

    showColl(cursor);
  }
 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);
   }
 }
Пример #5
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);
  }
Пример #6
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;
  }
Пример #7
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;
  }
Пример #8
0
  public MongoCursor<Document> getTraceCursor(
      String network,
      String station,
      String location,
      String channel,
      String startStr,
      String endStr) {

    String year, month;
    MongoCursor<Document> cursor = null;
    try {
      year = Helpers.getYearString(startStr, sdfToSecond);
      month = Helpers.getMonthString(startStr, sdfToSecond);

      MongoCollection<Document> collection =
          database.getCollection(
              Helpers.getTraceCollectionName(network, station, location, channel, year, month));

      // db.AK__2015.aggregate([
      // { $match: { $and:[ {"_id" : {"$gte" : "ANM_2015-11-23T00:31"}}, {"_id" : {"$lte" :
      // "ANM_2015-11-23T00:32"}}]}},
      // { $unwind : "$BHZ" },
      // { $project: {_id:0, "BHZ":1}},
      // { $sort: {"BHZ.et":1}}
      // ]).pretty()

      // db.AK_B_2015.aggregate([{ $match: { $and:[{"_id" :
      // {$gte:"ANM__2015-12-02T09:53"}},{_id:{$lte:"ANM_2015-12-02T09:58"}}]}},{ $unwind : "$BHZ"
      // },{ $project: {_id:1,"BHZ":1}}]).pretty()

      String gteCond =
          station
              + "_"
              + location
              + "_"
              + Helpers.convertDateBefore1Min(startStr, sdfToSecond, sdfToMinute);
      String lteCond =
          station + "_" + location + "_" + Helpers.convertDate(endStr, sdfToSecond, sdfToMinute);

      Bson match = match(and(gte("_id", gteCond), lte("_id", lteCond)));

      Bson unwind = unwind("$" + channel);
      Bson project = project(new Document("_id", 0).append(channel, 1));
      Bson sort = sort(new Document(channel + ".et", 1));

      List<Bson> aggregateParams = new ArrayList<>();
      aggregateParams.add(match);
      aggregateParams.add(unwind);
      aggregateParams.add(project);
      aggregateParams.add(sort);

      cursor = collection.aggregate(aggregateParams).iterator();

    } catch (ParseException e) {
      logger.error("start or end parameter format is 'yyyy-MM-dd'T'HH:mm:ss.SSSS'. {}", e);
      return null;
    }

    return cursor;
  }
Пример #9
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);
    }
  }
Пример #10
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);
    }
  }
Пример #11
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();
  }
Пример #12
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);
  }
Пример #13
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);
 }
Пример #14
0
      @FinishBundle
      public void finishBundle(Context ctx) throws Exception {
        MongoDatabase mongoDatabase = client.getDatabase(spec.database());
        MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(spec.collection());

        mongoCollection.insertMany(batch);

        batch.clear();
      }
Пример #15
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);
   }
 }
Пример #16
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();
    }
  }
Пример #17
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);
 }
Пример #18
0
 public static void saveGroups() {
   MongoCollection<Document> collection = MongoConnection.getCollection("perms", "groups");
   for (Group group : groups) {
     collection.replaceOne(
         eq("group", group.getName()),
         new Document("group", group.getName())
             .append("permissions", group.permissions)
             .append("inherits", group.inherits));
   }
 }
  private static void importToMongoDB(
      String host, int port, String databaseName, String collectionName, List<Document> docList) {
    MongoClient client = new MongoClient(host, port);
    MongoDatabase database = client.getDatabase(databaseName);
    MongoCollection<Document> collection = database.getCollection(collectionName);

    collection.insertMany(docList);

    client.close();
  }
Пример #20
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();
 }
  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;
  }
Пример #22
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();
  }
Пример #23
0
  public void putRecipeSummary(RecipeSummary recipeSummary) {
    MongoCollection<BsonDocument> collectionRecipeSummary =
        database.getCollection("recipeSummary", BsonDocument.class);
    BsonDocument bsonDocument = BsonDocument.parse(recipeSummary.toJson());
    bsonDocument.put("_id", new BsonString(recipeSummary.getRecipeId()));
    LOG.info("put bsonDocument = {}", bsonDocument.toString());

    collectionRecipeSummary.replaceOne(
        eq("_id", recipeSummary.getRecipeId()), bsonDocument, new UpdateOptions().upsert(true));
    //        collectionRecipeSummary.insertOne(bsonDocument);
  }
Пример #24
0
 /**
  * Creates indices for faster lookups in the database
  *
  * @since 1.12.15
  */
 public static void createIndices() {
   MongoDatabase lettersdb = mongoClient.getDatabase(databaseName);
   for (final String name : lettersdb.listCollectionNames()) {
     System.out.println("collection:" + name);
     if (name.startsWith(prefixCollectionPrefix)) {
       MongoCollection<Document> prefixCollection = lettersdb.getCollection(name);
       prefixCollection.createIndex(ascending(prefixAttribute));
     }
   }
   MongoCollection<Document> wordCollection = lettersdb.getCollection(wordCollectionName);
   wordCollection.createIndex(ascending(wordAttribute));
 }
Пример #25
0
  public void upsertTraceStats(Document key, Document doc) {

    options.upsert(true);
    try {
      traceStatsColl.updateOne(key, doc, options);
    } catch (MongoWriteException e) {
      if (e.getCode() == 11000) {
        options.upsert(false);
        traceStatsColl.updateOne(key, doc, options);
      }
    }
  }
Пример #26
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;
   }
 }
Пример #27
0
 public void clearAllBookings() {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
     final Document emptyDoc = new Document();
     coll.deleteMany(emptyDoc);
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(MessagesEnum.CLEAR_ALL_BOOKINGS_FAILED.getMessage(), e);
   }
 }
 /** {@inheritDoc} */
 @Override
 public void disableGroup(String groupName) {
   if (groupName == null || groupName.isEmpty()) {
     throw new IllegalArgumentException("Groupname cannot be null nor empty");
   }
   if (!existGroup(groupName)) {
     throw new GroupNotFoundException(groupName);
   }
   for (Document document : collection.find(BUILDER.getGroupName(groupName))) {
     Object enabled = BUILDER.getEnable(false);
     collection.updateOne(document, new Document(MONGO_SET, enabled));
   }
 }
  public void push(String id, Comment comment) {
    MongoCollection<Document> commentCollection = mongoDatabase.getCollection("posts");

    Document document = new Document();
    document.put("user", comment.getUser());
    document.put("text", comment.getText());
    document.put("date", comment.getDate());

    commentCollection.updateOne(
        new Document("_id", new ObjectId(id)),
        new Document("$push", new Document("comments", document)),
        new UpdateOptions().upsert(false));
  }
Пример #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;
 }