Beispiel #1
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);
  }
  @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 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;
  }
  public List<DBObject> getSourceBrowsers() {

    DBObject groupFields = new BasicDBObject("_id", "$device");
    groupFields.put("sum", new BasicDBObject("$sum", "$sum"));
    DBObject group = new BasicDBObject("$group", groupFields);
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("sum", 1));

    List<DBObject> pipeline = Arrays.asList(group, sort);

    // allowDiskUse
    AggregationOptions options =
        AggregationOptions.builder().allowDiskUse(true).batchSize(10000).build();
    Cursor cursor = device.aggregate(pipeline, options);

    List<DBObject> list = new ArrayList<DBObject>();
    while (cursor.hasNext()) {
      DBObject object = cursor.next();
      DBObject newObj = new BasicDBObject();
      newObj.put("device", object.get("_id"));
      newObj.put("sum", object.get("sum"));
      list.add(newObj);
    }
    cursor.close();
    return list;
  }
  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;
      }
    }
  }
  @Test(groups = "dev")
  public void timestampExistingFieldTest() throws EventDeliveryException, ParseException {
    ctx.put(MongoSink.MODEL, MongoSink.CollectionModel.dynamic.name());
    String tsField = "createdOn";
    ctx.put(MongoSink.TIMESTAMP_FIELD, tsField);
    MongoSink sink = new MongoSink();
    Configurables.configure(sink, ctx);

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

    JSONObject msg = new JSONObject();
    msg.put("age", 11);
    msg.put("birthday", new Date().getTime());
    String dateText = "2013-02-19T14:20:53+08:00";
    msg.put(tsField, dateText);

    Transaction tx;

    for (int i = 0; i < 10; i++) {
      tx = channel.getTransaction();
      tx.begin();
      msg.put("name", "test" + i);
      JSONObject header = new JSONObject();
      header.put(MongoSink.COLLECTION, "my_events");
      header.put(MongoSink.DB_NAME, "dynamic_db");

      Event e = EventBuilder.withBody(msg.toJSONString().getBytes(), header);
      channel.put(e);
      tx.commit();
      tx.close();
    }
    sink.process();
    sink.stop();

    msg.put(tsField, MongoSink.dateTimeFormatter.parseDateTime(dateText).toDate());
    for (int i = 0; i < 10; i++) {
      msg.put("name", "test" + i);

      System.out.println("i = " + i);

      DB db = mongo.getDB("dynamic_db");
      DBCollection collection = db.getCollection("my_events");
      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"));
      assertTrue(dbObject.get(tsField) instanceof Date);
      System.out.println("ts = " + dbObject.get(tsField));
    }
  }
  public UpdateResponse update(String alias, ShowToSave showToSave) {
    DBObject show = findShow(alias);

    if (!show.get("alias").toString().equals(showToSave.getAlias())) {
      updateDenormalizedFields(show.get("alias").toString(), showToSave.getAlias());
    }

    mapper.map(showToSave, show);
    db.getCollection("show").update(aliasOrId(alias), show);
    return new UpdateResponse(true);
  }
  public OkResponse contact(String alias, MailToShow mailToSend) {
    ValidationResult validate = captchaValidator.validate(mailToSend.getCaptcha());
    if (!validate.isSuccess()) {
      throw new IllegalArgumentException("Rosszul megadott Captcha: " + validate.toString());
    }
    MimeMessage mail = mailSender.createMimeMessage();
    try {
      MimeMessageHelper helper = new MimeMessageHelper(mail, false);

      String body =
          "----- Ez a levél a tilos.hu műsoroldaláról lett küldve-----\n"
              + "\n"
              + "A form kitöltője a "
              + mailToSend.getFrom()
              + " email-t adta meg válasz címnek, de ennek valódiságát nem ellenőriztük."
              + "\n"
              + "-------------------------------------"
              + "\n"
              + mailToSend.getBody();

      helper.setFrom("*****@*****.**");
      helper.setReplyTo(mailToSend.getFrom());
      helper.setSubject("[tilos.hu] " + mailToSend.getSubject());
      helper.setText(body);

      DBObject one = db.getCollection("show").findOne(aliasOrId(alias));
      if (one == null) {
        throw new IllegalArgumentException("No such show: " + alias);
      }
      ShowDetailed detailed = mapper.map(one, ShowDetailed.class);

      detailed
          .getContributors()
          .forEach(
              contributor -> {
                DBObject dbAuthor =
                    db.getCollection("author").findOne(aliasOrId(contributor.getAuthor().getId()));

                if (dbAuthor.get("email") != null) {
                  try {
                    helper.setTo((String) dbAuthor.get("email"));
                  } catch (MessagingException e) {
                    throw new RuntimeException(e);
                  }
                  mailSender.send(mail);
                }
              });
    } catch (Exception e) {
      throw new InternalErrorException("Can't send the email message: " + e.getMessage(), e);
    }
    return new OkResponse("Üzenet elküldve.");
  }
  @Test
  public void testSpecial() {
    DBCollection c = _db.getCollection("testSpecial");
    c.insert(new BasicDBObject("x", 1));
    c.insert(new BasicDBObject("x", 2));
    c.insert(new BasicDBObject("x", 3));
    c.ensureIndex("x");

    for (DBObject o : c.find().sort(new BasicDBObject("x", 1)).addSpecial("$returnKey", 1))
      assertTrue(o.get("_id") == null);

    for (DBObject o : c.find().sort(new BasicDBObject("x", 1))) assertTrue(o.get("_id") != null);
  }
  /** this is really for embedded objects */
  private int putObject(String name, DBObject o) {
    if (o == null) throw new NullPointerException("can't save a null object");

    if (DEBUG)
      System.out.println(
          "putObject : " + name + " [" + o.getClass() + "]" + " # keys " + o.keySet().size());

    if (_flipped) throw new IllegalStateException("already flipped");
    final int start = _buf.position();

    byte myType = OBJECT;
    if (o instanceof List) myType = ARRAY;

    if (_handleSpecialObjects(name, o)) return _buf.position() - start;

    if (name != null) {
      _put(myType, name);
    }

    final int sizePos = _buf.position();
    _buf.putInt(0); // leaving space for this.  set it at the end

    List transientFields = null;

    if (myType == OBJECT) {
      if (o.containsField("_id")) _putObjectField("_id", o.get("_id"));

      {
        Object temp = o.get("_transientFields");
        if (temp instanceof List) transientFields = (List) temp;
      }
    }

    for (String s : o.keySet()) {

      if (s.equals("_id")) continue;

      if (transientFields != null && transientFields.contains(s)) continue;

      Object val = o.get(s);

      _putObjectField(s, val);
    }
    _buf.put(EOO);

    _buf.putInt(sizePos, _buf.position() - sizePos);
    return _buf.position() - start;
  }
Beispiel #11
0
  /**
   * Determines the read preference that should be used for the given command.
   *
   * @param command the {@link DBObject} representing the command
   * @param requestedPreference the preference requested by the client.
   * @return the read preference to use for the given command. It will never return {@code null}.
   * @see com.mongodb.ReadPreference
   */
  ReadPreference getCommandReadPreference(DBObject command, ReadPreference requestedPreference) {
    String comString = command.keySet().iterator().next();

    if (comString.equals("getnonce") || comString.equals("authenticate")) {
      return ReadPreference.primaryPreferred();
    }

    boolean primaryRequired;

    // explicitly check mapreduce commands are inline
    if (comString.equals("mapreduce")) {
      Object out = command.get("out");
      if (out instanceof BSONObject) {
        BSONObject outMap = (BSONObject) out;
        primaryRequired = outMap.get("inline") == null;
      } else primaryRequired = true;
    } else {
      primaryRequired = !_obedientCommands.contains(comString.toLowerCase());
    }

    if (primaryRequired) {
      return ReadPreference.primary();
    } else if (requestedPreference == null) {
      return ReadPreference.primary();
    } else {
      return requestedPreference;
    }
  }
  @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");
  }
  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;
  }
Beispiel #14
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();
  }
  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;
  }
Beispiel #16
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 ShowDetailed get(String alias) {
    DBObject one = db.getCollection("show").findOne(aliasOrId(alias));
    if (one == null) {
      throw new NotFoundException("No such show");
    }
    ShowDetailed detailed = mapper.map(one, ShowDetailed.class);

    Date now = new Date();
    for (SchedulingSimple ss : detailed.getSchedulings()) {
      if (ss.getValidFrom().compareTo(now) < 0 && ss.getValidTo().compareTo(now) > 0)
        ss.setText(schedulingTextUtil.create(ss));
    }
    if (detailed.getContributors() != null) {
      for (ShowContribution contributor : detailed.getContributors()) {
        if (contributor.getAuthor() != null) {
          avatarLocator.locateAvatar(contributor.getAuthor());
        }
      }
    }
    long mixCount =
        db.getCollection("mix")
            .count(new BasicDBObject("show.ref", new DBRef(db, "show", one.get("_id").toString())));
    detailed.getStats().mixCount = (int) mixCount;
    detailed.setUrls(processUrls(detailed.getUrls()));
    return detailed;
  }
  @Test(groups = "dev")
  public void sinkDynamicDbTest() throws EventDeliveryException {
    ctx.put(MongoSink.MODEL, MongoSink.CollectionModel.dynamic.name());
    MongoSink sink = new MongoSink();
    Configurables.configure(sink, ctx);

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

    JSONObject msg = new JSONObject();
    msg.put("age", 11);
    msg.put("birthday", new Date().getTime());

    Transaction tx;

    for (int i = 0; i < 10; i++) {
      tx = channel.getTransaction();
      tx.begin();
      msg.put("name", "test" + i);
      JSONObject header = new JSONObject();
      header.put(MongoSink.COLLECTION, "my_events");
      header.put(MongoSink.DB_NAME, "dynamic_db");

      Event e = EventBuilder.withBody(msg.toJSONString().getBytes(), header);
      channel.put(e);
      tx.commit();
      tx.close();
    }
    sink.process();
    sink.stop();

    for (int i = 0; i < 10; i++) {
      msg.put("name", "test" + i);

      System.out.println("i = " + i);

      DB db = mongo.getDB("dynamic_db");
      DBCollection collection = db.getCollection("my_events");
      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"));
    }
  }
  @Test
  public void findATweetFromXebia() throws Exception {

    DBObject query = new BasicDBObject("from_user_name", "XebiaFR");

    DBObject result = collection.findOne(query);

    assertThat(result).isNotNull();

    String from_user_id = (String) result.get("from_user_id");
    String from_user_name = (String) result.get("from_user_name");
    Date created_at = (Date) result.get("created_at");
    String text = (String) result.get("text");

    Tweet tweet = new Tweet(from_user_id, from_user_name, created_at, text);
    assertThat(tweet.getUserName()).isEqualTo("XebiaFR");
  }
Beispiel #20
0
  // 获得一天的转换漏斗
  public List<DBObject> getConversionFunnel(String date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    DBObject match = null;
    try {
      match = new BasicDBObject("$match", new BasicDBObject("date", sdf.parse(date)));
    } catch (ParseException e) {

    }
    DBObject groupFields = new BasicDBObject("_id", "");
    groupFields.put("step1sum", new BasicDBObject("$sum", "$step1"));
    groupFields.put("step2sum", new BasicDBObject("$sum", "$step2"));
    groupFields.put("step3sum", new BasicDBObject("$sum", "$step3"));

    DBObject group = new BasicDBObject("$group", groupFields);
    // DBObject sort = new BasicDBObject("$sort", new BasicDBObject("sum", 1));

    List<DBObject> pipeline = Arrays.asList(match, group);

    // allowDiskUse
    AggregationOptions options =
        AggregationOptions.builder().allowDiskUse(true).batchSize(10000).build();
    Cursor cursor = CF.aggregate(pipeline, options);

    List<DBObject> list = new ArrayList<DBObject>();
    while (cursor.hasNext()) {
      DBObject object = cursor.next();
      DBObject newObj = new BasicDBObject();
      //            DBObject _id = (DBObject)object.get("_id");
      //            newObj.put("date",sdf.format(_id.get("$date")));
      DBObject newObj1 = new BasicDBObject();
      newObj1.put("step", "访问本站");
      newObj1.put("num", object.get("step1sum"));
      list.add(newObj1);
      DBObject newObj2 = new BasicDBObject();
      newObj2.put("step", "浏览商品");
      newObj2.put("num", object.get("step2sum"));
      list.add(newObj2);

      DBObject newObj3 = new BasicDBObject();
      newObj3.put("step", "完成交易");
      newObj3.put("num", object.get("step3sum"));
      list.add(newObj3);
    }
    cursor.close();
    return list;
  }
Beispiel #21
0
  @Override
  public String read(String hash) throws InterruptedException {
    DBObject dbObject = new BasicDBObject("hash", hash);
    DBObject obj = hashColl.findOne(dbObject, hashObject());

    Thread.sleep(300);

    if (obj != null) return obj.get("way").toString();
    else return null;
  }
  boolean _isMaster(DBObject res) {
    Object x = res.get("ismaster");
    if (x == null) throw new IllegalStateException("ismaster shouldn't be null: " + res);

    if (x instanceof Boolean) return (Boolean) x;

    if (x instanceof Number) return ((Number) x).intValue() == 1;

    throw new IllegalArgumentException("invalid ismaster [" + x + "] : " + x.getClass().getName());
  }
  public QueryResult<VariantAnalysisInfo> getAnalysisInfo(String studyId) {

    long start = System.currentTimeMillis();
    QueryResult<VariantAnalysisInfo> qres = new QueryResult<>();
    VariantAnalysisInfo vi = new VariantAnalysisInfo();

    DBCollection coll = db.getCollection("sources");
    DBCollection collV = db.getCollection("variants");

    long dbStart = System.currentTimeMillis();
    DBObject study = coll.findOne(new BasicDBObject("alias", studyId));

    if (study != null) {
      Iterator<Object> it = ((BasicDBList) study.get("samples")).iterator();

      while (it.hasNext()) {
        vi.addSample((String) it.next());
      }

      BasicDBObject gs = (BasicDBObject) study.get("globalStats");

      for (String elem : gs.keySet()) {
        if (!elem.equalsIgnoreCase("consequenceTypes")) {
          double val = gs.getDouble(elem);
          vi.addGlobalStats(elem, val);
        } else {

          BasicDBObject cts = (BasicDBObject) gs.get("consequenceTypes");
          for (String ct : cts.keySet()) {
            vi.addConsequenceType(ct, cts.getInt(ct));
          }
        }
      }
    }
    qres.setDbTime(System.currentTimeMillis() - dbStart);

    qres.setResult(Arrays.asList(vi));

    qres.setTime(System.currentTimeMillis() - start);

    return qres;
  }
 private EventEntry(DBObject dbObject) {
   this.serializedPayload = dbObject.get(SERIALIZED_PAYLOAD_PROPERTY);
   this.payloadType = (String) dbObject.get(PAYLOAD_TYPE_PROPERTY);
   this.payloadRevision = (String) dbObject.get(PAYLOAD_REVISION_PROPERTY);
   this.serializedMetaData = dbObject.get(META_DATA_PROPERTY);
   this.eventIdentifier = (String) dbObject.get(EVENT_IDENTIFIER_PROPERTY);
   this.sequenceNumber = (Long) dbObject.get(EVENT_SEQUENCE_NUMBER_PROPERTY);
   this.timestamp = (long) dbObject.get(EVENT_TIMESTAMP_PROPERTY);
 }
  public int crearId() {
    DBObject obj = null;
    DBCollection coleccionUsuario = conectarMongo();
    DBCursor cur = coleccionUsuario.find();
    int mayor = 0;
    while (cur.hasNext()) {
      // System.out.println(cur.next());
      obj = cur.next();
      if (Integer.parseInt(obj.get("id_u").toString()) > mayor) {
        mayor = Integer.parseInt(obj.get("id_u").toString());
      }
    }
    // System.out.println(obj.get("nombre"));

    if (obj != null) {
      return mayor + 1;
    } else {
      return 1;
    }
  }
 public static <T> T get(final DBObject dbo, final String key) {
   final String[] keys = key.split("\\.");
   DBObject current = dbo;
   Object result = null;
   for (int i = 0; i < keys.length; i++) {
     result = current.get(keys[i]);
     if (i + 1 < keys.length) {
       current = (DBObject) result;
     }
   }
   return (T) result;
 }
 /**
  * @param tags tags map
  * @return a good secondary by tag value or null if can't find one
  */
 ServerAddress getASecondary(DBObject tags) {
   // store the reference in local, so that it doesn't change out from under us while looping
   List<Tag> tagList = new ArrayList<Tag>();
   for (String key : tags.keySet()) {
     tagList.add(new Tag(key, tags.get(key).toString()));
   }
   Node node = _replicaSetHolder.get().getASecondary(tagList);
   if (node != null) {
     return node.getServerAddress();
   }
   return null;
 }
Beispiel #28
0
  // --------------------------------------------------------------------------------
  private void drawTreeRoot(Tree _tree, DBObject data) {
    // reset tree
    _tree.removeAll();

    if (data != null) {
      TreeItem root = new TreeItem(_tree, SWT.NONE);
      root.setText(data.get("_id") + "");
      root.setImage(documentImage);
      root.setData("fieldName", "");
      root.setData("value", data.get("_id"));
      fieldNameTreeItemMap.put("", root);

      boolean expand = (data.keySet().size() < 35);
      drawItem("", root, data.toMap(), expand);
    }

    nameText.setText("");
    typeCombo.select(0);
    typeCombo.setEnabled(false);
    valueText.setText("");
    updateButton.setEnabled(false);
  }
  @Override
  public List<TestData> getList() {
    try {
      DB db = MongoDBProvider.getInstance().getDB();
      DBCollection coll = db.getCollection("testdata");
      List<TestData> results = new ArrayList<TestData>();

      DBCursor cursor = coll.find();
      while (cursor.hasNext()) {
        DBObject result = cursor.next();
        TestData testData =
            new TestData((String) result.get("source"), (Integer) result.get("fails"));
        results.add(testData);
      }

      return results;

    } catch (MongoException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return null;
  }
  @Override
  public TestData get(String className) {
    DB db = null;
    try {
      db = MongoDBProvider.getInstance().getDB();
      DBCollection coll = db.getCollection("testdata");

      BasicDBObject query = new BasicDBObject();
      query.put("source", className);
      DBCursor cursor = coll.find(query);

      if (cursor.hasNext()) {
        DBObject result = cursor.next();
        TestData testData =
            new TestData((String) result.get("source"), (Integer) result.get("fails"));
        return testData;
      }
    } catch (MongoException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return new TestData(className, 0);
  }