Exemple #1
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;
  }
Exemple #2
0
  public List<User> getAllBookings(final String boxName) {
    /**
     * Creating 'nextUserEmailInQueue' as string buffer because value cannot be reassigned as it is
     * declared as final
     */
    final List<User> users = new ArrayList<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.BOX_NAME, boxName);
      final Document sortCr = new Document();
      sortCr.put(DBConstants.BOOKED_DATE_N_TIME, 1);
      final ArrayList<Document> lstBkngs =
          coll.find(findCr).sort(sortCr).into(new ArrayList<Document>());

      for (final Document document : lstBkngs) {
        final User user = new User();
        user.setEmail(document.getString(DBConstants.EMAIL));
        user.setBookedDateNTime(document.getDate(DBConstants.BOOKED_DATE_N_TIME));
        user.setDateNTime(document.getDate(DBConstants.DATE_N_TIME));
        user.setBookingId(document.getString(DBConstants.BOOKING_ID));
        users.add(user);
      }
    } 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 users;
  }
Exemple #3
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); // 没有数据就执行添加操作
    }
  }
 /**
  * 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);
 }
  public static void main(String[] args) {
    Document demo1 = new Document();

    demo1.put("_id", 6);
    demo1.put("age", 21);
    demo1.put("gender", "female");
    demo1.put("name", "周芷若");

    insertTest1(demo1);
  }
  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));
  }
 @Override
 public Document generateIdIfAbsentFromDocument(final Document document) {
   if (!documentHasId(document)) {
     document.put(ID_FIELD_NAME, idGenerator.generate());
   }
   return document;
 }
Exemple #8
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);
    }
  }
Exemple #9
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);
  }
Exemple #10
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;
  }
  // update mongo
  public static void readEquip(MongoDatabase db) {
    // MongoCollection equipCollection = db.getCollection("equipements");
    try (InputStream inputStream =
            CsvToMongoDb.class.getResourceAsStream("/batch/csv/equipements.csv");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
      reader
          .lines()
          .skip(1)
          .filter(line -> line.length() > 0)
          .map(line -> line.split(","))
          .forEach(
              columns -> {
                String instNumero = columns[2];
                System.out.println("instNumero = " + instNumero);
                String numero = columns[4];
                System.out.println("numero = " + numero);
                String nom = columns[5];
                System.out.println("nom = " + nom);
                String type = columns[7];
                System.out.println("type = " + type);
                String famille = columns[9];
                System.out.println("famille = " + famille);

                Document searchQuery = new Document();
                searchQuery.put("_id", instNumero);

                Document equipArDoc = new Document();

                equipArDoc.put(
                    "$push",
                    new Document(
                        "equipements",
                        new Document()
                            .append("numero", numero)
                            .append("nom", nom)
                            .append("type", type)
                            .append("famille", famille)));

                db.getCollection("installations").updateOne(searchQuery, equipArDoc);
              });
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
Exemple #12
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);
   }
 }
Exemple #13
0
 public void updateBooking(String bookingId) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
     // update user booking time
     final Document filterQuery = new Document();
     filterQuery.put(DBConstants.BOOKING_ID, bookingId);
     final Document updateQuery = new Document();
     final Document updateSet = new Document();
     updateSet.put(DBConstants.DATE_N_TIME, new Date());
     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.UPDATE_USER_FAILED.getMessage(), e);
   }
 }
  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;
  }
 /**
  * 按条件查询出单个对象
  *
  * @param tableName
  * @param timeValue
  * @param appId
  * @param appVersion
  * @param appChannel
  * @param appPlatform
  * @param tenantId
  * @param network
  * @param carrier
  * @return
  */
 public Document findOneBy(
     String tableName,
     String timeValue,
     String appId,
     String appVersion,
     String appChannel,
     String appPlatform,
     String network,
     String carrier,
     String tenantId) {
   MongoDatabase db = mongoClient.getDatabase(appId);
   Document matchFields = new Document();
   matchFields.put("timeValue", timeValue);
   matchFields.put("appVersion", appVersion);
   matchFields.put("appChannel", appChannel);
   matchFields.put("appPlatform", appPlatform);
   matchFields.put("network", network);
   matchFields.put("carrier", carrier);
   if (tenantId != null && !tenantId.trim().isEmpty()) {
     matchFields.put("tenantId", tenantId);
   } else { // 当相同的条件下有tenantId对应一条数据,无tenantId对应一条数据,所以要加上matchFields.put("tenantId",
            // null);,以免查询出两条数据,会照成结果错误
     matchFields.put("tenantId", null);
   }
   FindIterable<Document> iterable = db.getCollection(tableName).find(matchFields);
   if (iterable.iterator().hasNext()) {
     return iterable.first();
   } else {
     return null;
   }
 }
  @Override
  public Document decode(final BsonReader reader, final DecoderContext decoderContext) {
    Document document = new Document();

    reader.readStartDocument();
    while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
      String fieldName = reader.readName();
      document.put(fieldName, readValue(reader, decoderContext));
    }

    reader.readEndDocument();

    return document;
  }
Exemple #17
0
 public boolean closeBooking(final String bookingId) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
     final Document booking = new Document();
     booking.put(DBConstants.BOOKING_ID, bookingId);
     coll.deleteOne(booking);
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(MessagesEnum.CLOSE_BOOKING_FAILED.getMessage(bookingId), e);
   }
   return true;
 }
Exemple #18
0
 private void calculateWeights(
     final Index index, final com.mongodb.client.model.IndexOptions indexOptions) {
   Document weights = new Document();
   for (Field field : index.fields()) {
     if (field.weight() != -1) {
       if (field.type() != IndexType.TEXT) {
         throw new MappingException(
             "Weight values only apply to text indexes: " + Arrays.toString(index.fields()));
       }
       weights.put(field.value(), field.weight());
     }
   }
   if (!weights.isEmpty()) {
     indexOptions.weights(weights);
   }
 }
Exemple #19
0
 public String getBoxOwner(final String boxName) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOXES);
     final Document bson = new Document();
     bson.put(DBConstants.BOX_NAME, boxName);
     final List<Document> boxes = coll.find(bson).into(new ArrayList<Document>());
     if (boxes == null || (boxes != null && boxes.size() == 0)) {
       return "";
     } else {
       // '0' index is accessed because boxes are uniquely maintained at DB level
       return boxes.get(0).getString(DBConstants.OWNER);
     }
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(MessagesEnum.RETRIVAL_FAILED.getMessage(), e);
   }
 }
Exemple #20
0
 public String getUserNameWithEmail(final String email) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_USERS);
     final Document bson = new Document();
     bson.put(DBConstants.EMAIL, email);
     final List<Document> users = coll.find(bson).into(new ArrayList<Document>());
     if (users == null || (users != null && users.size() == 0)) {
       return "";
     } else {
       // '0' index is accessed because email is uniquely maintained at DB level
       return users.get(0).getString(DBConstants.USER_NAME);
     }
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(MessagesEnum.RETRIVAL_FAILED.getMessage(email), e);
   }
 }
Exemple #21
0
 public boolean hasWhatsNewsBeenRead(String hostname) {
   try {
     final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
     final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_WHATSNEW);
     final Document bson = new Document();
     bson.put(DBConstants.HOST_NAME, hostname);
     final List<Document> documents = coll.find(bson).into(new ArrayList<Document>());
     if (documents == null || (documents != null && documents.size() == 0)) {
       return false;
     } else {
       // '0' index is accessed because hostname is uniquely maintained at DB level
       return documents.get(0).getString(DBConstants.READ) != null;
     }
   } catch (Exception e) {
     if (e instanceof com.mongodb.MongoTimeoutException) {
       throw new ApplicationException(MessagesEnum.MONGODB_IS_DOWN.getMessage(), e);
     }
     throw new ApplicationException(e);
   }
 }
  /**
   * 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);
  }
  @SuppressWarnings("unchecked")
  public List<Comment> get(String id) {
    MongoCollection<Document> commentCollection = mongoDatabase.getCollection("posts");
    List<Comment> comments = new ArrayList<Comment>();
    Document query = new Document();
    query.put("_id", new ObjectId(id));

    Document document = commentCollection.find(query).first();

    if (document != null) {
      ArrayList<Document> list = (ArrayList<Document>) document.get("comments");

      for (int i = 0; i < list.size(); i++) {
        Document com = (Document) list.get(i);
        Comment comment = new Comment();
        comment.setUser(com.getString("user"));
        comment.setText(com.getString("text"));
        comment.setDate(com.getDate("date"));
        comments.add(comment);
      }
    }

    return comments;
  }
Exemple #24
0
 public Map<String, List<String>> getBoxes() {
   final Map<String, List<String>> boxesMap = new LinkedHashMap<String, List<String>>();
   final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
   final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOXES);
   final Document sortCr = new Document();
   sortCr.put(DBConstants.OWNER, 1);
   final FindIterable<Document> cursor = coll.find().sort(sortCr);
   cursor.forEach(
       new Block<Document>() {
         @Override
         public void apply(final Document document) {
           List<String> boxes;
           if (!boxesMap.containsKey(document.getString(DBConstants.OWNER))) {
             boxes = new ArrayList<String>();
             boxes.add(document.getString(DBConstants.BOX_NAME));
           } else {
             boxes = boxesMap.get(document.get(DBConstants.OWNER).toString());
             boxes.add(document.getString(DBConstants.BOX_NAME));
           }
           boxesMap.put(document.getString(DBConstants.OWNER), boxes);
         }
       });
   return boxesMap;
 }
  /**
   * 缓存每条汇总结果
   *
   * @param cacheMap
   * @param tuple
   */
  private void doCacheEventDetailInfo(
      Map<String, Document> cacheMap, Tuple2<String, Integer> tuple) {
    logger.debug("come into doCacheEventDetailInfo ==> " + tuple._1() + " <--> " + tuple._2());
    // 解析表名:字段名1、字段名2:字段名1值:timeValue:appId:appVersion(tenantId)
    String keys[] = tuple._1().split(":");
    String tableName = keys[0];
    String fieldName1 = keys[1];
    String fieldName2 = keys[2];
    String fieldName1Value = keys[3];
    String timeValue = keys[4];
    String appId = keys[5];
    String appVersion = keys[6];
    String tenantId =
        (keys.length == 8 && keys[7] != null && !keys[7].trim().isEmpty()) ? (keys[7]) : "";
    String tenantIdKey =
        (keys.length == 8 && keys[7] != null && !keys[7].trim().isEmpty())
            ? (":" + keys[7])
            : ""; // 存在tenantId就加到keyStr中去

    Document versionDetailDoc = null;

    String newUserFromChannal = null;
    String updateUserFromChannal = null;
    String updateUserFromVersion = null;
    if ("newUserFromChannal".equals(fieldName1)) {
      newUserFromChannal = fieldName1Value;
    }
    if ("updateUserFromChannal".equals(fieldName1)) {
      updateUserFromChannal = fieldName1Value;
    }
    if ("updateUserFromVersion".equals(fieldName1)) {
      updateUserFromVersion = fieldName1Value;
    }
    String keyStr =
        tableName
            + ":"
            + timeValue
            + ":"
            + appId
            + ":"
            + appVersion
            + ":"
            + fieldName1
            + ":"
            + fieldName1Value
            + tenantIdKey;
    // 如果缓存命中,使用缓存的对象
    if (cacheMap.containsKey(keyStr)) {
      versionDetailDoc = cacheMap.get(keyStr);
    } else {
      versionDetailDoc =
          versionDetailDao.findOneBy(
              tableName,
              timeValue,
              appId,
              appVersion,
              newUserFromChannal,
              updateUserFromChannal,
              updateUserFromVersion,
              tenantId);
    }

    if (versionDetailDoc == null) {
      VersionDetail versionDetail = new VersionDetail();
      versionDetail.setAppId(appId);
      versionDetail.setAppVersion(appVersion);
      versionDetail.setTimeValue(timeValue);
      if (tenantId != null && !tenantId.trim().isEmpty()) {
        versionDetail.setTenantId(tenantId);
      }
      Gson gson = new Gson();
      versionDetailDoc = Document.parse(gson.toJson(versionDetail));
      ObjectId objId = new ObjectId();
      versionDetailDoc.put("_id", objId);
      versionDetailDoc.put(fieldName1, fieldName1Value);
    }
    if (versionDetailDoc.get(fieldName2) == null) {
      versionDetailDoc.put(fieldName2, tuple._2());
    } else {
      long fieldValue = 0;
      try {
        fieldValue = versionDetailDoc.getLong(fieldName2);
      } catch (ClassCastException e) {
        fieldValue = (long) versionDetailDoc.getInteger(fieldName2);
      }

      versionDetailDoc.put(fieldName2, (long) (fieldValue + tuple._2()));
    }
    cacheMap.put(keyStr, versionDetailDoc);
    return;
  }
  /**
   * 缓存每条汇总结果
   *
   * @param cacheMap
   * @param tuple
   */
  private void doCacheEventDetailInfo(
      Map<String, Document> cacheMap, Tuple2<String, Integer> tuple) {
    logger.debug("come into doCacheEventDetailInfo ==> " + tuple._1() + " <--> " + tuple._2());
    // 解析表名:字段名:timeValue:appId:appVersion:appChannel:appPlatform:eventId:paramKey:paramValue(tenantId)
    String keys[] = tuple._1().split(":");
    String tableName = keys[0];
    String fieldName = keys[1];
    String timeValue = keys[2];
    String appId = keys[3];
    String appVersion = keys[4];
    String appChannel = keys[5];
    String appPlatform = keys[6];
    String eventId = keys[7];
    String paramKey = keys[8];
    String paramValue = keys[9];
    String tenantId =
        (keys.length == 11 && keys[10] != null && !keys[10].trim().isEmpty()) ? (keys[10]) : "";
    String tenantIdKey =
        (keys.length == 11 && keys[10] != null && !keys[10].trim().isEmpty())
            ? (":" + keys[10])
            : ""; // 存在tenantId就加到keyStr中去

    Document eventDetailInfoDoc = null;

    String keyStr =
        tableName
            + ":"
            + timeValue
            + ":"
            + appId
            + ":"
            + appVersion
            + ":"
            + appChannel
            + ":"
            + appPlatform
            + ":"
            + eventId
            + ":"
            + paramKey
            + ":"
            + paramValue
            + tenantIdKey;
    // 如果缓存命中,使用缓存的对象
    if (cacheMap.containsKey(keyStr)) {
      eventDetailInfoDoc = cacheMap.get(keyStr);
    } else {
      eventDetailInfoDoc =
          eventDetailInfoDao.findOneBy(
              tableName,
              timeValue,
              appId,
              appVersion,
              appChannel,
              appPlatform,
              eventId,
              paramKey,
              paramValue,
              tenantId);
    }

    if (eventDetailInfoDoc == null) {
      EventDetailInfo eventDetailInfoTemp = new EventDetailInfo();
      eventDetailInfoTemp.setEventId(eventId);
      eventDetailInfoTemp.setTimeValue(timeValue);
      eventDetailInfoTemp.setAppId(appId);
      if (tenantId != null && !tenantId.trim().isEmpty()) {
        eventDetailInfoTemp.setTenantId(tenantId);
      }
      Gson gson = new Gson();
      eventDetailInfoDoc = Document.parse(gson.toJson(eventDetailInfoTemp));
      ObjectId objId = new ObjectId();
      eventDetailInfoDoc.put("_id", objId);
      eventDetailInfoDoc.put("appVersion", appVersion);
      eventDetailInfoDoc.put("appChannel", appChannel);
      eventDetailInfoDoc.put("appPlatform", appPlatform);
      eventDetailInfoDoc.put("paramKey", paramKey);
      eventDetailInfoDoc.put("paramValue", paramValue);
    }
    if (eventDetailInfoDoc.get(fieldName) == null) {
      eventDetailInfoDoc.put(fieldName, (long) tuple._2());
    } else {
      long fieldValue = 0;
      try {
        fieldValue = eventDetailInfoDoc.getLong(fieldName);
      } catch (ClassCastException e) {
        fieldValue = (long) eventDetailInfoDoc.getInteger(fieldName);
      }
      eventDetailInfoDoc.put(fieldName, (long) (fieldValue + tuple._2()));
    }
    cacheMap.put(keyStr, eventDetailInfoDoc);
    return;
  }
Exemple #27
0
  public Map<String, Booking> getAllBookings() {
    final Map<String, Booking> bookings = new LinkedHashMap<String, Booking>();
    try {
      final MongoDatabase mdb = MongoDBConnManager.getInstance().getConnection();
      final MongoCollection<Document> coll = mdb.getCollection(DBConstants.COLL_BOOKING);
      List<Document> aggregates = new ArrayList<Document>();

      Document join = new Document();
      Document sortCr = new Document();

      /*Document lookup = new Document();
      lookup.put("from", DBConstants.COLL_BOXES);
      lookup.put("localField", DBConstants.BOX_NAME);
      lookup.put("foreignField", DBConstants.BOX_NAME);
      lookup.put("as", "join_for_teamname");*/

      Document lookup2 = new Document();
      lookup2.put("from", DBConstants.COLL_USERS);
      lookup2.put("localField", DBConstants.EMAIL);
      lookup2.put("foreignField", DBConstants.EMAIL);
      lookup2.put("as", "join_for_username");

      // join.put("$lookup", lookup);
      join.put("$lookup", lookup2);
      sortCr.put("$sort", new Document(DBConstants.TEAM_NAME, 1));

      aggregates.add(join);
      aggregates.add(sortCr);

      final ArrayList<Document> bookingsFromDB =
          coll.aggregate(aggregates).into(new ArrayList<Document>());

      for (final Document document : bookingsFromDB) {
        final User user = new User();
        user.setUserName(
            ((Document) document.get("join_for_username", List.class).get(0))
                .getString(DBConstants.USER_NAME));
        user.setEmail(document.getString(DBConstants.EMAIL));
        user.setTeamName(
            ((Document) document.get("join_for_username", List.class).get(0))
                .getString(DBConstants.TEAM_NAME));
        user.setBookedDateNTime(document.getDate(DBConstants.BOOKED_DATE_N_TIME));
        user.setDateNTime(document.getDate(DBConstants.DATE_N_TIME));
        user.setEstimatedUsage(document.getInteger(DBConstants.ESTIMATED_USAGE));
        user.setBookingId(document.getString(DBConstants.BOOKING_ID));
        if (!bookings.containsKey(document.getString(DBConstants.BOX_NAME))) {
          Booking bkng = new Booking();
          bkng.setBoxName(document.getString(DBConstants.BOX_NAME));
          bkng.setBoxOwner(getBoxOwner(document.getString(DBConstants.BOX_NAME)));
          bkng.addUserToQueue(user);
          bookings.put(document.getString(DBConstants.BOX_NAME), bkng);
        } else {
          Booking bkng = bookings.get(document.getString(DBConstants.BOX_NAME));
          bkng.addUserToQueue(user);
        }
      }
      // sort users based on timestamps
      for (Booking bkng : bookings.values()) {
        Collections.sort(bkng.getUsersInQueue());
      }
    } 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 bookings;
  }