Ejemplo n.º 1
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);
       }
     }
   }
 }
Ejemplo n.º 2
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));
        }
      }
    }
  }
Ejemplo n.º 3
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);
    }
  }
Ejemplo n.º 4
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);
  }
Ejemplo n.º 5
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;
  }
Ejemplo n.º 6
0
  public static void main(String[] args) {

    System.setProperty("javax.net.ssl.trustStore", args[0]);
    System.setProperty("javax.net.ssl.trustStorePassword", args[1]);
    MongoClientOptions.Builder options = builder().sslEnabled(true).sslInvalidHostNameAllowed(true);
    String uri = "mongodb://127.0.0.1:27017/";
    MongoClientURI connectionString = new MongoClientURI(uri, options);
    MongoClient mongoClient = new MongoClient(connectionString);

    // with username and password

    char[] pwd = "mypasswrd!".toCharArray();

    MongoCredential credential =
        MongoCredential.createCredential(
            "myadmin", "admin", pwd); // user "myadmin" on admin database

    List<MongoCredential> credentials = Collections.singletonList(credential);

    List<ServerAddress> hosts =
        Arrays.asList(
            new ServerAddress("mongodb01.host.dblayer.com:10054"),
            new ServerAddress("mongodb02.host.1.dblayer.com:10071"));

    mongoClient = new MongoClient(hosts, credentials, options.build());
    MongoDatabase foxtrot = mongoClient.getDatabase("foxtrot");
    MongoIterable<String> collectionNames = foxtrot.listCollectionNames();
  }
Ejemplo n.º 7
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;
   }
 }
Ejemplo n.º 8
0
  public void getCommitCount() throws Exception {

    MongoClient mongoClient = new MongoClient(MongoInfo.getMongoServerIp(), 27017);
    MongoDatabase database = mongoClient.getDatabase("ghcrawlerV3");
    FindIterable<Document> issueIterable = database.getCollection("commitnumber").find();
    Connection connection = MysqlInfo.getMysqlConnection();
    connection.setAutoCommit(false);
    JsonParser parser = new JsonParser();
    for (Document document : issueIterable) {
      String json = document.toJson();
      JsonObject repoJsonObject = parser.parse(json).getAsJsonObject();
      int commit = repoJsonObject.get("commitnumber").getAsInt();
      String full_name = repoJsonObject.get("fn").getAsString();
      System.out.println(full_name);
      String sql = "update repotest set commit = ? where full_name = ?";
      PreparedStatement stmt = connection.prepareStatement(sql);
      stmt.setInt(1, commit);
      stmt.setString(2, full_name);
      stmt.execute();
    }

    connection.commit();
    connection.close();
    mongoClient.close();
  }
Ejemplo n.º 9
0
  public void getIssueAndPull() throws Exception {
    MongoClient mongoClient = new MongoClient(MongoInfo.getMongoServerIp(), 27017);
    MongoDatabase database = mongoClient.getDatabase("ghcrawlerV3");
    FindIterable<Document> issueIterable = database.getCollection("issueandpull").find();
    Connection connection = MysqlInfo.getMysqlConnection();
    connection.setAutoCommit(false);
    String sql =
        "update repotest set open_issues = ?,closed_issues = ?,open_pull=?,closed_pull=? where full_name = ?";
    PreparedStatement stmt = connection.prepareStatement(sql);
    JsonParser parser = new JsonParser();
    for (Document document : issueIterable) {
      String json = document.toJson();
      JsonObject repoIssue = parser.parse(json).getAsJsonObject();
      int openIssue = repoIssue.get("openissue").getAsInt();
      int closedIssue = repoIssue.get("closedissue").getAsInt();
      int openPull = repoIssue.get("openpull").getAsInt();
      int closedPull = repoIssue.get("closedpull").getAsInt();
      String repoName = repoIssue.get("fn").getAsString();
      System.out.println(repoName);
      stmt.setInt(1, openIssue);
      stmt.setInt(2, closedIssue);
      stmt.setInt(3, openPull);
      stmt.setInt(4, closedPull);
      stmt.setString(5, repoName);

      stmt.execute();
    }
    connection.commit();
    connection.close();
    mongoClient.close();
  }
  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);
    }
  }
Ejemplo n.º 11
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;
  }
Ejemplo n.º 12
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); // 没有数据就执行添加操作
    }
  }
Ejemplo n.º 13
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 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();
  }
Ejemplo n.º 16
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);
  }
Ejemplo n.º 17
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();
  }
Ejemplo n.º 18
0
  public void getCollaborators() throws Exception {
    // get mysql connection
    Connection connection = MysqlInfo.getMysqlConnection();
    connection.setAutoCommit(false);
    String conSql = "insert into collaborator(user_id,repo_id) values(?,?);";
    PreparedStatement conStmt = connection.prepareStatement(conSql);
    String repoSql = "update repotest set collaborator = ? where id = ?";
    PreparedStatement repoStmt = connection.prepareStatement(repoSql);

    // get repos from mongo
    MongoClient mongoClient = new MongoClient(MongoInfo.getMongoServerIp(), 27017);
    MongoDatabase database = mongoClient.getDatabase("ghcrawlerV3");
    FindIterable<Document> repoIterable = database.getCollection("repo").find();
    JsonParser parser = new JsonParser();
    Map<String, Integer> repoMap = new HashMap<String, Integer>();
    for (Document document : repoIterable) {
      String json = document.toJson();
      JsonObject repoJsonObject = parser.parse(json).getAsJsonObject();
      int id = repoJsonObject.get("id").getAsInt();
      String full_name = repoJsonObject.get("full_name").getAsString();
      System.out.println(id);
      repoMap.put(full_name, id);
    }

    Map<Integer, Integer> collaboratorMap = new HashMap<Integer, Integer>();

    FindIterable<Document> collaboratorIterable = database.getCollection("assignees").find();
    for (Document document : collaboratorIterable) {
      String json = document.toJson();
      JsonObject contriJsonObject = parser.parse(json).getAsJsonObject();
      int id = contriJsonObject.get("id").getAsInt();
      String repoName = contriJsonObject.get("fn").getAsString();
      int repo_id = repoMap.get(repoName);
      conStmt.setInt(1, id);
      conStmt.setInt(2, repo_id);
      conStmt.execute();

      if (collaboratorMap.containsKey(repo_id)) {
        collaboratorMap.put(repo_id, collaboratorMap.get(repo_id) + 1);
      } else {
        collaboratorMap.put(repo_id, 1);
      }
    }

    Set<Integer> keySet = collaboratorMap.keySet();
    for (Integer repoId : keySet) {
      int contri_count = collaboratorMap.get(repoId);
      repoStmt.setInt(1, contri_count);
      repoStmt.setInt(2, repoId);
      repoStmt.execute();
    }

    mongoClient.close();
    connection.commit();
    conStmt.close();
    repoStmt.close();
    connection.close();
  }
Ejemplo n.º 19
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);
 }
Ejemplo n.º 20
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();
      }
Ejemplo n.º 21
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();
    }
  }
Ejemplo n.º 22
0
 /**
  * Retrieves the names of the collections in a database.
  *
  * @param databaseName the name of the database
  * @return a {@link Set} of collection names
  */
 protected Set<String> getCollectionNames(final String databaseName) {
   final MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);
   final Set<String> collectionSet = new HashSet<>();
   final MongoCursor<String> cursor = mongoDatabase.listCollectionNames().iterator();
   while (cursor.hasNext()) {
     collectionSet.add(cursor.next());
   }
   return collectionSet;
 }
  @Override
  public Object execute() throws Exception {

    MongoDatabase adminDatabase = mongoService.getMongoClient().getDatabase(database);
    Document document = adminDatabase.runCommand(new Document("dbStats", 1));
    System.out.println(document.toJson(new JsonWriterSettings(true)));

    return null;
  }
  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();
  }
Ejemplo n.º 25
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;
   }
 }
Ejemplo n.º 26
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();
 }
Ejemplo n.º 27
0
  public static void main(String args[]) {

    // MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
    MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("PROJ");

    MongoCollection<Document> collection = database.getCollection("proj");

    // *************************************************
    // permet de compter le nombre d'élément dans la base
    // **************************************************
    //        System.out.print(collection.count());

    // ************************************
    // permet d'afficher toutes les donnés
    // ************************************
    //        FindIterable<Document> iterable = collection.find();
    //        iterable.forEach(new Block<Document>() {
    //            @Override
    //            public void apply(final Document document) {
    //                System.out.println(document);
    //            }
    //        });

    // ************************************************************************
    // permet d'afficher les données ou le borrower est la republique d'albanie
    // ************************************************************************
    //        FindIterable<Document> iterable = collection.find(
    //                new Document("borrower", "REPUBLIC OF ALBANIA"));
    //        iterable.forEach(new Block<Document>() {
    //            @Override
    //            public void apply(final Document document) {
    //                System.out.println(document);
    //            }
    //        });

    // ****************************************************************
    // permet de trouver les marjor secteur energy and mining > 40%
    // ****************************************************************
    //        FindIterable<Document> iterable = collection.find(
    //                new Document("majorsector_percent.Name", "Energy and
    // mining").append("majorsector_percent.Percent",new Document("$lt", 40)));
    //        iterable.forEach(new Block<Document>() {
    //            @Override
    //            public void apply(final Document document) {
    //                System.out.println(document);
    //            }
    //        });
    // *****************************************************
    // permet d'ouvrir l'interface
    // ****************************************************/
    MainWindow page = new MainWindow();
  }
Ejemplo n.º 28
0
    @Override
    public long getEstimatedSizeBytes(PipelineOptions pipelineOptions) {
      MongoClient mongoClient = new MongoClient(new MongoClientURI(spec.uri()));
      MongoDatabase mongoDatabase = mongoClient.getDatabase(spec.database());

      // get the Mongo collStats object
      // it gives the size for the entire collection
      BasicDBObject stat = new BasicDBObject();
      stat.append("collStats", spec.collection());
      Document stats = mongoDatabase.runCommand(stat);
      return Long.valueOf(stats.get("size").toString());
    }
Ejemplo n.º 29
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));
 }
Ejemplo n.º 30
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);
         }
       });
 }