@Test(groups = "dev")
  public void autoWrapTest() throws EventDeliveryException {
    ctx.put(MongoSink.AUTO_WRAP, Boolean.toString(true));
    ctx.put(MongoSink.DB_NAME, "test_wrap");

    MongoSink sink = new MongoSink();
    Configurables.configure(sink, ctx);

    sink.setChannel(channel);
    sink.start();

    Transaction tx = channel.getTransaction();
    tx.begin();
    String msg =
        "2012/10/26 11:23:08 [error] 7289#0: *6430831 open() \"/usr/local/nginx/html/50x.html\" failed (2: No such file or directory), client: 10.160.105.161, server: sg15.redatoms.com, request: \"POST /mojo/ajax/embed HTTP/1.0\", upstream: \"fastcgi://unix:/tmp/php-fpm.sock:\", host: \"sg15.redatoms.com\", referrer: \"http://sg15.redatoms.com/mojo/mobile/package\"";

    Event e = EventBuilder.withBody(msg.getBytes());
    channel.put(e);
    tx.commit();
    tx.close();

    sink.process();
    sink.stop();

    DB db = mongo.getDB("test_wrap");
    DBCollection collection = db.getCollection("test_log");
    DBCursor cursor = collection.find(new BasicDBObject(MongoSink.DEFAULT_WRAP_FIELD, msg));
    assertTrue(cursor.hasNext());
    DBObject dbObject = cursor.next();
    assertNotNull(dbObject);
    assertEquals(dbObject.get(MongoSink.DEFAULT_WRAP_FIELD), msg);
    mongo.dropDatabase("test_wrap");
  }
  @Test(dataProvider = "ids")
  public void generateSchedule(String id) throws ParseException, UnknownHostException {
    DBObject query = (DBObject) JSON.parse("{_id:\"" + id + "\" }");
    DBObject filter =
        (DBObject)
            JSON.parse(
                "{"
                    + "\"FpML.trade.swap.swapStream.calculationPeriodDates.effectiveDate\":1,"
                    + "\"FpML.trade.swap.swapStream.calculationPeriodDates.terminationDate\":1,"
                    + "\"FpML.trade.swap.swapStream.calculationPeriodDates.calculationPeriodFrequency\":1,"
                    + "\"FpML.trade.swap.swapStream.calculationPeriodDates.calculationPeriodDatesAdjustments\":1,"
                    + "}");

    DBCursor dbCursor = fpmls.find(query, filter);
    DBObject dates = dbCursor.next();
    DBObject stream1 = get(dates, "FpML.trade.swap.swapStream.0.calculationPeriodDates");

    List<org.jquantlib.time.Date> dates11 = generateCouponDates(stream1);
    List<Date> dates12 = (List<Date>) cashflows.findOne(query).get("P");

    for (Date date : dates12)
      Assert.assertTrue(dates11.contains(new org.jquantlib.time.Date(date)));

    DBObject stream2 = get(dates, "FpML.trade.swap.swapStream.1.calculationPeriodDates");
    List<org.jquantlib.time.Date> dates21 = generateCouponDates(stream2);
    List<Date> dates22 = (List<Date>) cashflows.findOne(query).get("R");

    for (Date date : dates22)
      Assert.assertTrue(dates21.contains(new org.jquantlib.time.Date(date)));
  }
  @Test(groups = "dev")
  public void sinkSingleModelTest() throws EventDeliveryException {
    ctx.put(MongoSink.MODEL, MongoSink.CollectionModel.single.name());

    MongoSink sink = new MongoSink();
    Configurables.configure(sink, ctx);

    sink.setChannel(channel);
    sink.start();

    Transaction tx = channel.getTransaction();
    tx.begin();
    JSONObject msg = new JSONObject();
    msg.put("name", "test");
    msg.put("age", 11);
    msg.put("birthday", new Date().getTime());

    Event e = EventBuilder.withBody(msg.toJSONString().getBytes());
    channel.put(e);
    tx.commit();
    tx.close();

    sink.process();
    sink.stop();

    DB db = mongo.getDB("test_events");
    DBCollection collection = db.getCollection("test_log");
    DBCursor cursor = collection.find(new BasicDBObject(msg));
    assertTrue(cursor.hasNext());
    DBObject dbObject = cursor.next();
    assertNotNull(dbObject);
    assertEquals(dbObject.get("name"), msg.get("name"));
    assertEquals(dbObject.get("age"), msg.get("age"));
    assertEquals(dbObject.get("birthday"), msg.get("birthday"));
  }
  private void customRoomLogin(ISFSEvent event) throws SFSLoginException {
    trace("Game Login by session");

    DBCollection users = AuthorizeExtension.users;

    BasicDBObject query = new BasicDBObject();
    query.put("session", generateSession);

    DBCursor cursor = users.find(query);

    if (!cursor.hasNext()) {
      trace("Game Login User not found!", generateSession);
      SFSErrorData data = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
      data.addParameter(userName);

      throw new SFSLoginException("Login failed for user: "******"Game Login User logged in!", generateSession);
      document = cursor.next();

      ISFSObject outData = (ISFSObject) event.getParameter(SFSEventParam.LOGIN_OUT_DATA);
      outData.putUtfString(SFSConstants.NEW_LOGIN_NAME, document.get("nickname").toString());

      Boolean isGuest = (Boolean) document.get("is_guest");
      if (isGuest == null) {
        isRegistered = true;
      } else {
        isRegistered = false;
      }
    }
  }
  private void handleUser(ISFSEvent event) {
    trace("Registered user logged in", userName);

    DBCollection users = AuthorizeExtension.users;

    BasicDBObject query = new BasicDBObject();
    query.put("email", userName);

    DBCursor cursor = users.find(query);

    if (!cursor.hasNext()) {
      trace("user not found");
      return;
    }

    document = cursor.next();

    String password_digest = (String) document.get("password_digest");

    if (!getApi().checkSecurePassword(session, password_digest, cryptedPass)) {
      trace("password wrong");
      return;
    }

    document.put("session", generateSession);
    users.update(query, document);

    isRegistered = true;
  }
Example #6
0
  /**
   * Returns a set containing all collections in the existing database.
   *
   * @return an set of names
   * @throws MongoException
   */
  public Set<String> getCollectionNames() {

    DBCollection namespaces = getCollection("system.namespaces");
    if (namespaces == null) throw new RuntimeException("this is impossible");

    Iterator<DBObject> i =
        namespaces.__find(
            new BasicDBObject(), null, 0, 0, 0, getOptions(), getReadPreference(), null);
    if (i == null) return new HashSet<String>();

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

    for (; i.hasNext(); ) {
      DBObject o = i.next();
      if (o.get("name") == null) {
        throw new MongoException("how is name null : " + o);
      }
      String n = o.get("name").toString();
      int idx = n.indexOf(".");

      String root = n.substring(0, idx);
      if (!root.equals(_name)) continue;

      if (n.indexOf("$") >= 0) continue;

      String table = n.substring(idx + 1);

      tables.add(table);
    }

    Collections.sort(tables);

    return new LinkedHashSet<String>(tables);
  }
Example #7
0
    public static void main(String[] args) throws UnknownHostException {
        MongoClient client = new MongoClient();
        DB db = client.getDB("hw31");
        DBCollection collection = db.getCollection("students");

        // create our pipeline operations, first with the $match
        DBObject match = new BasicDBObject("$match", new BasicDBObject("scores.type", "homework") );

        // $unwind op
        //DBObject unwind = new BasicDBObject("$unwind", "$scores");

        // Now the $group operation
        DBObject groupFields = new BasicDBObject( "_id", "$student_id");
        //groupFields.put("score", new BasicDBObject( "$min", "scores.$score"));
        DBObject group = new BasicDBObject("$group", groupFields);
//
//        // $sort operation
//        DBObject sortFields = new BasicDBObject("_id", 1).append("score", 1);
//        DBObject sort = new BasicDBObject("$sort", sortFields);

        // run aggregation
        AggregationOutput output = collection.aggregate(match, group);

        for(Iterator<DBObject> i = output.results().iterator(); i.hasNext();) {
            DBObject result = i.next();
            System.out.println(result);
//            collection.remove(QueryBuilder.start("student_id").is(result.get("_id"))
//                    .and("score").is(result.get("score")).and("type").is("homework").get());
        }

        System.out.println(collection.count());
    }
  public List<String> getActiveUsersFilterBy(
      String user, boolean withUsers, boolean withPublic, boolean isAdmin) {
    ArrayList<String> users = new ArrayList<String>();
    DBCollection coll = db().getCollection(M_TOKENS);
    BasicDBObject query = new BasicDBObject();
    query.put(
        "validity",
        new BasicDBObject(
            "$gt",
            System.currentTimeMillis()
                - getValidity())); // check token not updated since 10sec + status interval (15 sec)
    if (isAdmin) {
      if (withPublic && !withUsers) {
        query.put("isDemoUser", true);
      } else if (!withPublic && withUsers) {
        query.put("isDemoUser", false);
      }
    } else {
      query.put("isDemoUser", user.startsWith(ANONIM_USER));
    }
    DBCursor cursor = coll.find(query);
    while (cursor.hasNext()) {
      DBObject doc = cursor.next();
      String target = doc.get("user").toString();
      if (!user.equals(target)) users.add(target);
    }

    return users;
  }
  @Test
  public void testBatchWithActiveCursor() {
    DBCollection c = _db.getCollection("testBatchWithActiveCursor");
    c.drop();

    for (int i = 0; i < 100; i++) c.save(new BasicDBObject("x", i));

    try {
      DBCursor cursor = c.find().batchSize(2); // setting to 1, actually sets to 2 (why, oh why?)
      cursor.next(); // creates real cursor on server.
      cursor.next();
      assertEquals(0, cursor.numGetMores());
      cursor.next();
      assertEquals(1, cursor.numGetMores());
      cursor.next();
      cursor.next();
      assertEquals(2, cursor.numGetMores());
      cursor.next();
      cursor.next();
      assertEquals(3, cursor.numGetMores());
      cursor.batchSize(20);
      cursor.next();
      cursor.next();
      cursor.next();
      assertEquals(4, cursor.numGetMores());
    } catch (IllegalStateException e) {
      assertNotNull(e); // there must be a better way to detect this.
    }
  }
Example #10
0
  private String selectBooks(
      String schema, String collection, String title, String author, String isbn)
      throws UnknownHostException {
    System.out.println(schema);
    System.out.println(collection);
    System.out.println(title);
    System.out.println(author);
    List<String> l = new ArrayList<String>();
    MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance();
    Mongo mongo = mgr.getMongo();
    DB db = mongo.getDB(schema);

    try {
      DBCollection c = db.getCollection(collection);
      BasicDBObject titleQuery = new BasicDBObject();
      titleQuery.put("title", new BasicDBObject("$regex", title));
      BasicDBObject authorQuery = new BasicDBObject();
      authorQuery.put("author", new BasicDBObject("$regex", author));

      BasicDBList or = new BasicDBList();
      or.add(titleQuery);
      or.add(titleQuery);

      DBObject query = new BasicDBObject("$and", or);

      DBCursor cursor = c.find(titleQuery);
      while (cursor.hasNext()) l.add(cursor.next().toString());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    System.out.println(l);
    if (l.size() > 0) return l.toString();
    else return null;
  }
Example #11
0
  @Override
  public String IngresarJson(String nombreDB, String json, int clienteId)
      throws UnknownHostException {
    // TODO Auto-generated method stub
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB base = mongoClient.getDB(nombreDB);

    // Ya existe
    if (ExisteCliente(nombreDB, clienteId)) {
      //        	System.out.println("********************\n");
      //        	System.out.println("Ya existe cliente, error no se igresa el Json");
      //        	System.out.println("********************\n");
      return "Ya existe cliente, error no se igresa el Json";
    }

    // no existe el cliente
    DBCollection collection = base.getCollection("Json");
    BasicDBObject document = new BasicDBObject();
    document.put("id", clienteId);

    DBObject object = (DBObject) JSON.parse(json);
    document.put("json", object);
    // document.put("json",json);
    collection.insert(document);
    return "Ok";
  }
Example #12
0
  /**
   * Given the _id of a JSFile, return the file.
   *
   * @param id _id of the file to find
   * @return The file, if found, otherwise null
   */
  JSFile getJSFile(String id) {

    if (id == null) return null;

    DBCollection f = getDB().getCollection("_files");
    return (JSFile) (f.find(new ObjectId(id)));
  }
  public void introduceType(SpaceTypeDescriptor typeDescriptor) {

    DBCollection m = getConnection().getCollection(METADATA_COLLECTION_NAME);

    BasicDBObjectBuilder builder =
        BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY, typeDescriptor.getTypeName());
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream out = new ObjectOutputStream(bos);
      IOUtils.writeObject(
          out, SpaceTypeDescriptorVersionedSerializationUtils.toSerializableForm(typeDescriptor));

      builder.add(TYPE_DESCRIPTOR_FIELD_NAME, bos.toByteArray());

      WriteResult wr = m.save(builder.get());

      if (logger.isTraceEnabled()) logger.trace(wr);

      indexBuilder.ensureIndexes(typeDescriptor);

    } catch (IOException e) {
      logger.error(e);

      throw new SpaceMongoException(
          "error occurs while serialize and save type descriptor: " + typeDescriptor, e);
    }
  }
Example #14
0
  private List<String> selectViewCodes(String schema) throws UnknownHostException {
    // Initiate variables
    List<String> l = new ArrayList<String>();
    MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance();
    Mongo mongo = mgr.getMongo();
    DB db = mongo.getDB(schema);
    DBCollection collection = db.getCollection("views");

    // Compose NoSQL query
    BasicDBObject groupFiels = new BasicDBObject("_id", "$view_id");
    BasicDBObject group = new BasicDBObject("$group", groupFiels);
    BasicDBObject sortFiels = new BasicDBObject("_id", 1);
    BasicDBObject sort = new BasicDBObject("$sort", sortFiels);

    // Create the output
    AggregationOutput output = collection.aggregate(group, sort);
    Iterable<DBObject> results = output.results();
    for (DBObject result : results) {
      try {
        l.add(result.get("_id").toString());
      } catch (NullPointerException e) {
        System.out.println("Skipping NULL");
      }
    }

    // Return the result
    return l;
  }
  public void insertar(UsuarioOD Usuario) {

    DBCollection coleccionUsuario = conectarMongo();

    if (coleccionUsuario != null) {

      BasicDBObject usuario = new BasicDBObject();
      usuario.put("id_u", crearId());
      usuario.put("nombre", Usuario.getNombre());
      usuario.put("nombres", Usuario.getNombres());
      usuario.put("apellido", Usuario.getApellido());
      usuario.put("apellidos", Usuario.getApellidos());
      usuario.put("email", Usuario.getEmail());
      usuario.put("fecha", Usuario.getFecha());
      usuario.put("nick", Usuario.getNick());
      usuario.put("pais", Usuario.getPais());
      usuario.put("biografia", Usuario.getBiografia());
      usuario.put("sexo", Usuario.getSexo());
      usuario.put("clave", Usuario.getClave());
      coleccionUsuario.insert(usuario);

    } else {
      System.out.println("coleccion no existente");
    }
  }
Example #16
0
  @Override
  public String ActualizarJson(String nombreDB, String json, int clienteId)
      throws UnknownHostException {
    // TODO Auto-generated method stub

    if (!ExisteCliente(nombreDB, clienteId)) {
      //        	System.out.println("********************\n");
      //        	System.out.println("No existe el cliente, no se puede actualizar");
      //        	System.out.println("********************\n");
      return "No existe el cliente, no se puede actualizar";
    }
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB base = mongoClient.getDB(nombreDB);
    DBCollection collection = base.getCollection("Json");

    BasicDBObject document = new BasicDBObject();
    DBObject object = (DBObject) JSON.parse(json);
    document.put("id", clienteId);
    document.put("json", object);

    BasicDBObject query = new BasicDBObject().append("id", clienteId);

    collection.findAndModify(query, document);
    return "Cliente actualizado";
  }
Example #17
0
  public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("course");
    DBCollection lines = db.getCollection("dotNotationTest");
    lines.drop();
    Random rand = new Random();

    for (int i = 0; i < 10; i++) {
      lines.insert(
          new BasicDBObject("_id", i)
              .append(
                  "start",
                  new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10))
              .append(
                  "end",
                  new BasicDBObject("x", rand.nextInt(90) + 10)
                      .append("y", rand.nextInt(90) + 10)));
    }

    QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);

    DBCursor cursor =
        lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false));

    try {
      while (cursor.hasNext()) {
        DBObject cur = cursor.next();
        System.out.println(cur);
      }
    } finally {
      cursor.close();
    }
  }
  protected void createDatabase() {

    this.connect();

    log.write("MongoDBConnector - enablesharding for database..");

    log.write(
        this.mongoClient.getDB("admin").command(new BasicDBObject("enablesharding", ("twitter"))));

    log.write("MongoDBConnector - Creating hashed _id index..");
    dbCollection.createIndex(new BasicDBObject("_id", "hashed"));

    log.write("shardCollection twitter.tweets..");

    log.write(
        this.mongoClient
            .getDB("admin")
            .command(
                new BasicDBObject("shardCollection", "twitter.tweets")
                    .append("key", new BasicDBObject("_id", "hashed"))));

    log.write("MongoDBConnector - Creating indexes");

    // dbCollection.createIndex(new BasicDBObject("id", 1), new BasicDBObject("unique", true));
    dbCollection.createIndex(new BasicDBObject("text", "text"));

    log.write("MongoDBConnector - database created");
  }
  private boolean _handleSpecialObjects(String name, DBObject o) {

    if (o == null) return false;

    if (o instanceof DBCollection) {
      DBCollection c = (DBCollection) o;
      putDBPointer(name, c.getName(), Bytes.COLLECTION_REF_ID);
      return true;
    }

    if (!_dontRefContains(o) && name != null && o instanceof DBPointer) {
      DBPointer r = (DBPointer) o;
      putDBPointer(name, r._ns, (ObjectId) r._id);
      return true;
    }

    if (!(o instanceof List) && o.get(Bytes.NO_REF_HACK) != null) {
      o.removeField(Bytes.NO_REF_HACK);
      return false;
    }

    if (!_dontRefContains(o) && name != null && !(o instanceof List) && cameFromDB(o)) {
      putDBPointer(name, o.get("_ns").toString(), (ObjectId) (o.get("_id")));
      return true;
    }

    return false;
  }
Example #20
0
  public <T> T execute(Statement statement) throws BasicException {
    CompileResult result = this.compiler.compile(statement);

    for (AbstractRow row : result) {
      final DBObject bson = row.toBSON(statement.getArgs());
      final DB db = this.mongoClient.getDB(row.hasDatabase() ? row.getDatabase() : this.database);
      final DBCollection table = db.getCollection(row.getTable());
      final AbstractRow.Mode mode = row.getMode();

      switch (mode) {
        case insert:
          table.insert(bson);
          break;
        case select:
          break;
        case update:
          break;
        case delete:
          table.remove(bson);
          break;
        default:
          throw new RuntimeException("cannot recognize mode: " + mode);
      }
    }
    return null;
  }
Example #21
0
  public MongoCache(String addresses, String database, String collection, boolean slaveok) {

    List<ServerAddress> addr = new ArrayList<ServerAddress>();
    String[] hosts = addresses.split("\\n");

    for (int i = 0; i < hosts.length; i++) {
      try {
        addr.add(new ServerAddress(hosts[i]));
      } catch (UnknownHostException e) {
        e.printStackTrace();
      }
    }

    _mongo = new Mongo(addr);

    // if using replica sets then allow query of slaves instead of just master
    if (slaveok) {
      _mongo.slaveOk();
    }

    _db = _mongo.getDB(database);
    _coll = _db.getCollection(collection);

    // create the indexes
    _coll.ensureIndex(new BasicDBObject("key", 1));
    _coll.ensureIndex(new BasicDBObject("expires", 1));
    _coll.ensureIndex(new BasicDBObject("tags", 1));
  }
Example #22
0
  public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("course");
    DBCollection collection = db.getCollection("findCriteriaTest");
    collection.drop();

    for (int i = 0; i < 10; i++) {
      collection.insert(
          new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100)));
    }

    QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(90);
    // DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt",
    // 10).append("$lt", 90));

    System.out.println("\nCount:");
    long count = collection.count(builder.get());
    System.out.println(count);

    System.out.println("\nFind all:");
    DBCursor cursor = collection.find(builder.get());
    try {
      while (cursor.hasNext()) {
        DBObject cur = cursor.next();
        System.out.println(cur);
      }
    } finally {
      cursor.close();
    }
  }
Example #23
0
  @Override
  public String Json(String nombreDB, int clienteId) throws UnknownHostException, JSONException {
    // TODO Auto-generated method stub
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB base = mongoClient.getDB(nombreDB);

    DBCollection collection = base.getCollection("Json");
    BasicDBObject query = new BasicDBObject();
    query.put("id", clienteId);
    DBCursor cursor = collection.find(query);

    if (cursor.size() == 0) {
      //        	System.out.println("********************\n");
      //        	System.out.println("No existe el cliente, no se puede ingresar json");
      //        	System.out.println("********************\n");

      return "No existe el cliente, no se puede ingresar json";
    }
    // Existe el cliente

    DBObject objeto = (DBObject) cursor.next();

    DBObject json = (DBObject) objeto.get("json");
    //  DBObject j = JSON.parse(json.toString());
    JSONObject aj = new JSONObject(json.toString());

    return aj.toString();
  }
Example #24
0
  private String selectBooks(String collectionType, String type, String text, String schema)
      throws UnknownHostException {
    System.out.println(type);
    System.out.println(schema);
    List<String> l = new ArrayList<String>();
    MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance();
    Mongo mongo = mgr.getMongo();
    DB db = mongo.getDB(schema);
    // collectionType = "view"
    try {
      DBCollection collection = db.getCollection(collectionType);
      BasicDBObject searchQuery = new BasicDBObject();
      BasicDBObject regexQuery = new BasicDBObject();
      // regexQuery.put("title", new BasicDBObject("$regex", "^.*mi.*$").append("$options", "i"));

      regexQuery.put(type, new BasicDBObject("$regex", text).append("$options", "i"));

      DBCursor cursor = collection.find(regexQuery);
      while (cursor.hasNext()) l.add(cursor.next().toString());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    System.out.println(l);
    if (l.size() > 0) return l.toString();
    return "error";
  }
  @Test(expectedExceptions = NoSuchElementException.class)
  public void testShouldThrowNoSuchElementException() {
    DBCollection c = _db.getCollection("emptyCollection");

    DBCursor cursor = c.find();

    cursor.next();
  }
Example #26
0
 private void saveJson(String schema, String collection, String json) throws UnknownHostException {
   MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance();
   Mongo mongo = mgr.getMongo();
   DB db = mongo.getDB(schema);
   DBCollection c = db.getCollection(collection);
   DBObject dbObject = (DBObject) JSON.parse(json);
   c.insert(dbObject);
 }
 public boolean hasUserWithToken(String user, String token) {
   DBCollection coll = db().getCollection(M_TOKENS);
   BasicDBObject query = new BasicDBObject();
   query.put("user", user);
   query.put("token", token);
   DBCursor cursor = coll.find(query);
   return (cursor.hasNext());
 }
Example #28
0
 public void remove(String collection, DBObject query) {
   DBCollection dbCollection = getCollection(collection);
   dbCollection.remove(query);
   Jedis jedis = JedisManager.getJedis();
   jedis.zrem("expire", query.toString());
   jedis.hdel(collection, query.toString());
   JedisManager.returnJedis(jedis);
 }
Example #29
0
 /**
  * Adds privilege documents to the {@code system.users} collection in a database, which creates
  * database credentials in MongoDB.
  *
  * @param username
  * @param passwd
  * @param readOnly if true, user will only be able to read
  * @throws MongoException
  */
 public WriteResult addUser(String username, char[] passwd, boolean readOnly) {
   DBCollection c = getCollection("system.users");
   DBObject o = c.findOne(new BasicDBObject("user", username));
   if (o == null) o = new BasicDBObject("user", username);
   o.put("pwd", _hash(username, passwd));
   o.put("readOnly", readOnly);
   return c.save(o);
 }
Example #30
0
  public static void main(String[] args) throws UnknownHostException {

    MongoClient client = new MongoClient();
    DB database = client.getDB("school");
    DBCollection collection = database.getCollection("students");
    /*
     Hint/spoiler: With the new schema, this problem is a lot harder
     and that is sort of the point. One way is to find the lowest
     homework in code and then update the scores array with the low
     homework pruned. If you are struggling with the Node.js side of
     this, look at the .slice() operator, which can remove an element
     from an array in-place.
    */
    DBCursor cursor = collection.find();

    try {
      while (cursor.hasNext()) {
        BasicDBObject student = (BasicDBObject) cursor.next();

        int studentId = student.getInt("_id");
        String name = student.getString("name");
        BasicDBList scores = (BasicDBList) student.get("scores");
        System.out.printf("_id[%d], name[%s], scores%s %n", studentId, name, scores);

        DBObject scoreToRemove = null;
        double minScoreValue = 100.0;

        for (Object obj : scores) {
          BasicDBObject score = (BasicDBObject) obj;
          String type = score.getString("type");

          if (!"homework".equals(type)) {
            continue;
          }
          double curScoreValue = score.getDouble("score");
          System.out.printf("type[%s], current score value[%f] %n", type, curScoreValue);

          if (curScoreValue < minScoreValue) {
            scoreToRemove = score;
            minScoreValue = curScoreValue;
          }
        }
        System.out.printf("score to remove[%s] %n", scoreToRemove);

        if (scoreToRemove != null) {
          scores.remove(scoreToRemove);

          BasicDBObject query = new BasicDBObject("_id", studentId);
          BasicDBObject scoresUpdate =
              new BasicDBObject("$set", new BasicDBObject("scores", scores));
          WriteResult result = collection.update(query, scoresUpdate);
          System.out.printf("update count[%d] %n", result.getN());
        }
      }
    } finally {
      cursor.close();
    }
  }