Esempio n. 1
0
 /**
  * 按条件查询出单个对象
  *
  * @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;
   }
 }
 /**
  * 取得已出院未回访的用户
  *
  * @return
  */
 public List<record> GetleavehospitalRecords() {
   try {
     List<record> list = new ArrayList<record>();
     MongoDAO dao = MongoDAO.GetInstance();
     BasicDBObject cond = new BasicDBObject();
     cond.append("leaveHospital", new BasicDBObject("$eq", true));
     cond.append("followup", new BasicDBObject("$eq", false));
     FindIterable<Document> result = dao.GetCollection("records").find(cond);
     MongoCursor<Document> it = result.iterator();
     while (it.hasNext()) {
       Document doc = it.next();
       record fol = new record();
       fol.setAdmission_number(doc.getString("admission_number"));
       fol.setName(doc.getString("name"));
       fol.setWeixin_openid(doc.getString("weixin_openid"));
       fol.setLeaveTime(doc.getDate("leaveTime"));
       fol.setDisease(doc.getString("disease"));
       list.add(fol);
     }
     return list;
   } catch (Exception e) {
     e.printStackTrace();
     logger.error(e.toString());
     return null;
   }
 }
  @Override
  public List<Album> findAlbumByProperty(AlbumSearchType searchType, Object value) {

    List<Album> albums = new ArrayList<>();
    // Generic methods
    String whereClause = "";
    String valueClause = "";

    switch (searchType) {
      case ARTIST:
        whereClause = "artist.name";
        valueClause = value.toString();
        break;
      case SCORE:
        whereClause = "score";
        valueClause = value.toString();
        break;
      case TITLE:
        whereClause = "title";
        valueClause = value.toString();
        break;
      case GENRE:
        whereClause = "genre";
        valueClause = value.toString();
        break;
      default:
        System.out.println("Unknow search type");
        break;
    }

    try {

      FindIterable<Document> iterable =
          db.getCollection("album").find(new Document(whereClause, valueClause));
      iterable.forEach(
          new Block<Document>() {

            @Override
            public void apply(final Document document) {

              String title = document.getString("title");
              System.out.println(title);
              String genre = document.getString("genre");
              System.out.println(genre);
              String score = document.getString("score");
              System.out.println(score);
              String released = document.getString("released");
              System.out.println(released);
              String artists = document.get("artist").toString();
              System.out.println(artists);

              albums.add(new Album(title, score, genre, released, artists));
            }
          });

    } catch (Exception e) {
      e.printStackTrace();
    }
    return albums;
  }
 /**
  * 取得指定住院号的记录
  *
  * @param admissionNum 住院号
  * @return 住院记录
  */
 public record GetRecord(String admissionNum) {
   try {
     MongoDAO dao = MongoDAO.GetInstance();
     BasicDBObject cond = new BasicDBObject();
     cond.append("admission_number", new BasicDBObject("$eq", admissionNum));
     FindIterable<Document> result = dao.GetCollection("records").find(cond);
     MongoCursor<Document> it = result.iterator();
     if (it.hasNext()) {
       Document doc = it.next();
       record fol = new record();
       fol.setAdmission_number(doc.getString("admission_number"));
       fol.setName(doc.getString("name"));
       fol.setWeixin_openid(doc.getString("weixin_openid"));
       fol.setLeaveTime(doc.getDate("leaveTime"));
       fol.setInTime(doc.getDate("inTime"));
       fol.setDisease(doc.getString("disease"));
       return fol;
     }
     return null;
   } catch (Exception e) {
     e.printStackTrace();
     logger.error(e.toString());
     return null;
   }
 }
  public static void updateSQLDB(String mongoHost, int mongoPort, String mongoDb) {

    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    MongoDatabase db = mongoClient.getDatabase(mongoDb);
    FindIterable<Document> iterable = db.getCollection("flights").find();

    iterable.forEach(
        new Block<Document>() {
          public void apply(final Document document) {
            List<FlightLeg> legs = FlightToLegs.getInstance().getLegsFromFlightRecord(document);
            for (FlightLeg leg : legs) {
              FlightLegDAO legDAO = new FlightLegDAOJDBCImpl();
              int result = legDAO.create(leg);
              if (result == 0) {
                System.out.println(
                    "["
                        + result
                        + "]: ERROR Leg Creation:"
                        + leg.getDepartureAirportCode()
                        + "->"
                        + leg.getArrivalAirportCode()
                        + " DepartureUTC: "
                        + leg.getDepartureTimeUTC()
                        + " ArrivalUTC: "
                        + leg.getArrivalTimeUTC());
                System.exit(0);
              }
            }
          }
        });
    System.out.println("Done");
    mongoClient.close();
  }
  public static void updateMongoDB(
      String mongoHost, int mongoPort, String mongoDb, String flightsCol, String legsCollection) {

    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    MongoDatabase db = mongoClient.getDatabase(mongoDb);
    FindIterable<Document> iterable = db.getCollection(flightsCol).find();

    db.getCollection(legsCollection).createIndex(new Document("flightID", 1));
    db.getCollection(legsCollection).createIndex(new Document("departureAirport._id", 1));
    db.getCollection(legsCollection).createIndex(new Document("arrivalAirport._id", 1));
    db.getCollection(legsCollection).createIndex(new Document("effectiveDate", 1));
    db.getCollection(legsCollection).createIndex(new Document("discontinuedDate", 1));

    iterable.forEach(
        new Block<Document>() {
          public void apply(final Document document) {
            try {
              List<FlightLeg> legs = FlightToLegs.getInstance().getLegsFromFlightRecord(document);
              for (FlightLeg leg : legs) {
                FlightLegDAO legDAO = new FlightLegDAOMongoImpl();
                legDAO.setHost(mongoHost);
                legDAO.setPort(mongoPort);
                legDAO.setDB(mongoDb);
                legDAO.create(leg);
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        });
    System.out.println("Done");
    mongoClient.close();
  }
Esempio n. 7
0
 public Document findBy(String appId, String deviceId) {
   MongoDatabase db = mongoClient.getDatabase(appId);
   FindIterable<Document> iterable =
       db.getCollection("Widget").find(new Document("deviceId", deviceId));
   if (iterable.iterator().hasNext()) {
     return iterable.first();
   } else {
     return null;
   }
 }
Esempio n. 8
0
 public static void main(String[] args) {
   MongoClient mongoClient = new MongoClient("liangyanbo.com");
   MongoDatabase db = mongoClient.getDatabase("test");
   FindIterable<Document> iterable =
       db.getCollection("restaurants").find(new Document("borough", "Manhattan"));
   iterable.forEach(
       new Block<Document>() {
         public void apply(final Document document) {
           System.out.println(document);
         }
       });
 }
  @Override
  public SensorTypeInfo read(SensorType id) {

    SensorTypeInfo zettaDriver = new SensorTypeInfo();
    zettaDriver.setType(id.getCode());
    zettaDriver.setTypeName(id.getName());

    MongoCollection<Document> collection = CloudMongoDB.getInstance().getCollection("Drivers");

    // finds in database
    FindIterable<Document> users = collection.find(new Document("type", id.getCode()));
    SensorTypeInfo sensorInfo = SensorTypeInfoInstanceCreator.createInstance(users.first());
    // System.out.println(sensorInfo);

    return sensorInfo;
  }
Esempio n. 10
0
  @Override
  public List<Album> findAll() {
    List<Album> albums = new ArrayList<Album>();
    try {

      iterable = db.getCollection("album").find();
      iterable.forEach(
          new Block<Document>() {

            @Override
            public void apply(final Document document) {

              String title = document.getString("title");
              System.out.println(title);
              String genre = document.getString("genre");
              System.out.println(genre);
              String score = document.getString("score");
              System.out.println(score);
              String released = document.getString("released");
              System.out.println(released);
              String artists = document.get("artist").toString();
              System.out.println(artists);

              albums.add(new Album(title, score, genre, released, artists));
            }
          });

    } catch (Exception e1) {
      e1.printStackTrace();
    }
    return albums;
  }
 /**
  * 是否有同名记录
  *
  * @param name 患儿姓名
  * @return 住院记录
  */
 public boolean isRecordNameExists(String name) {
   try {
     MongoDAO dao = MongoDAO.GetInstance();
     BasicDBObject cond = new BasicDBObject();
     cond.append("name", new BasicDBObject("$eq", name));
     FindIterable<Document> result = dao.GetCollection("records").find(cond);
     MongoCursor<Document> it = result.iterator();
     if (it.hasNext()) {
       return true;
     }
     return false;
   } catch (Exception e) {
     e.printStackTrace();
     logger.error(e.toString());
     return false;
   }
 }
 /** Read user account from DB */
 public static UserAccount readFromDb(String userId) {
   if (!useMongoDB) {
     if (virtualDB.containsKey(userId)) {
       return virtualDB.get(userId);
     }
     return null;
   }
   if (db == null) {
     try {
       connect();
     } catch (ParseException e) {
       e.printStackTrace();
     }
   }
   FindIterable<Document> iterable =
       db.getCollection("user_accounts").find(new Document("userID", userId));
   if (iterable == null) {
     return null;
   }
   Document doc = iterable.first();
   return new UserAccount(userId, doc.getString("userName"), doc.getString("additionalInfo"));
 }
  public void find() throws UnknownHostException {

    // Connect to Mongo DB
    MongoClientURI mongoURI = new MongoClientURI("mongodb://localhost:27017");
    MongoClient mongo = new MongoClient(mongoURI);
    try {

      // Get "logs" collection from the "websites" DB.
      MongoDatabase db = mongo.getDatabase("websites");
      MongoCollection<Document> coll = db.getCollection("logs");

      // Find all DB object from the DB collection
      //			Document log = null;
      System.out.println(coll.count());
      FindIterable<Document> cursor = coll.find();

      // Loop for each db object of the cursor.
      //			while (cursor.iterator().hasNext()) {
      //				log = cursor.iterator().next();
      //				System.out.println(log.toString());
      //			}

      // JAVA 8 : these codes become
      //			cursor.forEach(new Block<Document>() {
      //
      //				@Override
      //				public void apply(Document t) {
      //					System.out.println(t.toString());
      //
      //				}
      //			});

      cursor.forEach((Block<Document>) t -> System.out.println(t.toString()));
    } finally {
      // close mongo connection
      mongo.close();
    }
  }
Esempio n. 14
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;
 }
Esempio n. 15
0
  public static Document meepDocumentBuilder(JsonObject arg, MongoCollection<Document> meepCol) {
    Document meep = new Document();
    if (arg.get("coordinates").isJsonNull()) return null;
    double longi =
        arg.getAsJsonObject("coordinates").getAsJsonArray("coordinates").get(0).getAsDouble();
    double lat =
        arg.getAsJsonObject("coordinates").getAsJsonArray("coordinates").get(1).getAsDouble();
    BasicDBObject aux = getCloseMeepsQuery(lat, longi);
    FindIterable<Document> auxCol = meepCol.find(aux);
    if (auxCol.first() != null) {
      System.out.println("Received valid tweet but too close to another");
      return null;
    }
    meep.append(
        "senderName", arg.getAsJsonObject("user").getAsJsonPrimitive("screen_name").getAsString());
    System.out.println(
        "Received valid tweet at "
            + lat
            + ","
            + longi
            + " posted by "
            + meep.getString("senderName"));
    meep.append("senderId", arg.getAsJsonObject("user").getAsJsonPrimitive("id").getAsInt());
    meep.append(
        "twitterUserPicture",
        arg.getAsJsonObject("user").getAsJsonPrimitive("profile_image_url").getAsString());
    meep.append("message", arg.getAsJsonPrimitive("text").getAsString());
    meep.append("type", "tweet");
    meep.append("isRoot", true);
    meep.append("commentCounter", 0);
    meep.append("likeCounter", 0);
    meep.append("viewCounter", 0);
    /*if(arg.getAsJsonObject("entities").has("media"))
        meep.append("picture", arg.getAsJsonObject("entities").getAsJsonObject("media").get("media_url").getAsString());
    else*/
    meep.append("picture", null);
    BasicDBList list = new BasicDBList();
    list.add(longi);
    list.add(lat);
    Document jobj = new Document();
    jobj.append("type", "Point");
    jobj.append("coordinates", list);

    meep.append("location", jobj);
    BasicDBList comments = new BasicDBList();
    meep.append("comments", comments);
    BasicDBList receipts = new BasicDBList();
    meep.append("receipts", receipts);
    BasicDBList registrees = new BasicDBList();
    meep.append("registrees", registrees);
    BasicDBList likes = new BasicDBList();
    meep.append("likes", likes);

    meep.append("categoryId", Category.TWITTER.getId());

    BasicDBList hashtags = new BasicDBList();
    HashtagController controller = new HashtagController();
    LinkedList<String> aux2 =
        controller.extractHashtags(arg.getAsJsonPrimitive("text").getAsString());
    for (String s : aux2) hashtags.add(s);
    meep.append("hashtags", hashtags);

    meep.append("isPublic", true);
    return meep;
  }