Example #1
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;
  }
Example #3
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;
    }
  }
  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;
  }
Example #5
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 #6
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;
  }
  @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 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;
  }
  @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 #12
0
 /**
  * Forces the master server to fsync the RAM data to disk, then lock all writes. The database will
  * be read-only after this command returns.
  *
  * @return result of the command execution
  * @throws MongoException
  * @mongodb.driver.manual reference/command/fsync/ fsync command
  */
 public CommandResult fsyncAndLock() {
   DBObject cmd = new BasicDBObject("fsync", 1);
   cmd.put("lock", 1);
   CommandResult result = getDB(ADMIN_DATABASE_NAME).command(cmd);
   result.throwOnError();
   return result;
 }
Example #13
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 #14
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 #15
0
 /**
  * Creates a collection with a given name and options. If the collection does not exist, a new
  * collection is created.
  *
  * <p>Possible options:
  *
  * <ul>
  *   <li><b>capped</b> ({@code boolean}) - Enables a collection cap. False by default. If enabled,
  *       you must specify a size parameter.
  *   <li><b>size</b> ({@code int}) - If capped is true, size specifies a maximum size in bytes for
  *       the capped collection. When capped is false, you may use size to preallocate space.
  *   <li><b>max</b> ({@code int}) - Optional. Specifies a maximum "cap" in number of documents for
  *       capped collections. You must also specify size when specifying max.
  *       <p>
  * </ul>
  *
  * <p>Note that if the {@code options} parameter is {@code null}, the creation will be deferred to
  * when the collection is written to.
  *
  * @param name the name of the collection to return
  * @param options options
  * @return the collection
  * @throws MongoException
  */
 public DBCollection createCollection(String name, DBObject options) {
   if (options != null) {
     DBObject createCmd = new BasicDBObject("create", name);
     createCmd.putAll(options);
     CommandResult result = command(createCmd);
     result.throwOnError();
   }
   return getCollection(name);
 }
Example #16
0
 /**
  * Forces the master server to fsync the RAM data to disk This is done automatically by the server
  * at intervals, but can be forced for better reliability.
  *
  * @param async if true, the fsync will be done asynchronously on the server.
  * @return result of the command execution
  * @throws MongoException
  * @mongodb.driver.manual reference/command/fsync/ fsync command
  */
 public CommandResult fsync(boolean async) {
   DBObject cmd = new BasicDBObject("fsync", 1);
   if (async) {
     cmd.put("async", 1);
   }
   CommandResult result = getDB(ADMIN_DATABASE_NAME).command(cmd);
   result.throwOnError();
   return result;
 }
Example #17
0
 public void updateDocument(String collection, DBObject query, DBObject document) {
   DBCollection dbCollection = getCollection(collection);
   dbCollection.update(query, document);
   Jedis jedis = JedisManager.getJedis();
   if (jedis.hexists(collection, query.toString())) {
     jedis.hset(collection, query.toString(), findOneNoCache(collection, query).toString());
     jedis.zadd("expire", System.currentTimeMillis() + 300000, collection + "_" + query);
   }
   JedisManager.returnJedis(jedis);
 }
Example #18
0
 public void delete(String collection, DBObject query) {
   DBCollection dbCollection = getCollection(collection);
   dbCollection.remove(query);
   Jedis jedis = JedisManager.getJedis();
   if (jedis.hexists(collection, query.toString())) {
     jedis.hdel(collection, query.toString(), findOneNoCache(collection, query).toString());
     jedis.zrem("expire", collection + "_" + query);
   }
   JedisManager.returnJedis(jedis);
 }
Example #19
0
    @Override
    public Object createObject(byte[] data, int offset) {
      DBObject dbo = new LazyBsonByte(data, offset, this);

      Iterator it = dbo.keySet().iterator();
      if (it.hasNext() && it.next().equals("$ref") && dbo.containsField("$id")) {
        return new DBRef(db, dbo);
      }
      return dbo;
    }
Example #20
0
 @Override
 public void write(String hash, String way) throws InterruptedException {
   DBObject dbObject = new BasicDBObject();
   dbObject.put("hash", hash);
   if (!isContain(dbObject)) {
     dbObject.put("way", way);
     hashColl.insert(dbObject);
   }
   Thread.sleep(300);
 }
Example #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;
  }
  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);
  }
Example #23
0
  public boolean nextObjectRow(DBObject obj) throws SQLException {
    boolean success;
    success = rs.next(); // FAUT RÉGLER LE NULL POINTER EXCEPTION ICI
    if (success) {
      obj = new DBObject();
      obj.setId(rs.getInt("id"));
      obj.setState(rs.getInt("state"));
    }

    return success;
  }
 public void updateValidity(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);
   while (cursor.hasNext()) {
     DBObject doc = cursor.next();
     doc.put("validity", System.currentTimeMillis());
     coll.save(doc, WriteConcern.SAFE);
   }
 }
 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;
 }
Example #26
0
 @Override
 public void savePlayer(GamePlayer gamePlayer) {
   service.submit(
       () -> {
         DBCursor cursor = collection.find(new BasicDBObject("uuid", gamePlayer.getUuid()));
         if (cursor.hasNext()) cursor.remove();
         String json = GSON.toJson(gamePlayer);
         DBObject object = new BasicDBObject();
         object.putAll((DBObject) JSON.parse(json));
         collection.insert(object);
       });
 }
 /**
  * @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;
 }
  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);
  }
 private DBObject getTagSet(String tagSetString) {
   DBObject tagSet = new BasicDBObject();
   if (tagSetString.length() > 0) {
     for (String tag : tagSetString.split(",")) {
       String[] tagKeyValuePair = tag.split(":");
       if (tagKeyValuePair.length != 2) {
         throw new IllegalArgumentException("Bad read preference tags: " + tagSetString);
       }
       tagSet.put(tagKeyValuePair[0].trim(), tagKeyValuePair[1].trim());
     }
   }
   return tagSet;
 }