/**
   * if hourlyjob has completed,item will insert to repository db.and partial file will delete,
   * dailydb will delete.
   *
   * @throws UnknownHostException
   */
  @Test
  public void t2() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT);
    DB dailyDb = mongoClient.getDB(dailyDbName);

    DBCollection hourlyCol = dailyDb.getCollection(AppConstants.MongoNames.HOURLY_JOB_COL_NAME);
    // must drop,or complete status detect will wrong.
    hourlyCol.drop();
    for (int idx = 24; idx > 12; idx--) {
      DBObject dbo =
          new BasicDBObject()
              .append(AppConstants.MongoNames.HOURLY_JOB_NUMBER_KEY, idx + "")
              .append(AppConstants.MongoNames.HOURLY_JOB_STATUS_KEY, "end");
      hourlyCol.insert(dbo);
    }
    new DailyCopyWorkVerticle.DailyCopyProcessor(
            mongoClient,
            dailyDbName,
            repositoryDbName,
            dailyPartialDir,
            new JsonObject().putNumber("dailydbreadgap", 1000))
        .process();
    mongoClient = new MongoClient(AppConstants.MONGODB_HOST, AppConstants.MONGODB_PORT);
    DB db = mongoClient.getDB(repositoryDbName);
    DBCollection col = db.getCollection(AppConstants.MongoNames.PAGE_VISIT_COL_NAME);
    Assert.assertEquals(10005, col.count());
    Assert.assertFalse(Files.exists(Paths.get(dailyPartialDir, dailyDbName)));
  }
  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 #3
0
  public void removeTestRunData(String testName, String testRunName) {
    {
      String collectionName = eventsCollectionName(testName, testRunName);
      if (db.collectionExists(collectionName)) {
        DBCollection collection = db.getCollection(collectionName);
        collection.drop();
      }
    }

    {
      String collectionName = resultsCollectionName(testName, testRunName);
      if (db.collectionExists(collectionName)) {
        DBCollection collection = db.getCollection(collectionName);
        collection.drop();
      }
    }

    {
      String collectionName = sessionsCollectionName(testName, testRunName);
      if (db.collectionExists(collectionName)) {
        DBCollection collection = db.getCollection(collectionName);
        collection.drop();
      }
    }
  }
  private void addQueryToStream(
      final Operation operation,
      final Timestamp<?> currentTimestamp,
      final DBObject update,
      final String collection)
      throws InterruptedException {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "addQueryToStream - operation [{}], currentTimestamp [{}], update [{}]",
          operation,
          currentTimestamp,
          update);
    }

    if (collection == null) {
      for (String name : slurpedDb.getCollectionNames()) {
        DBCollection slurpedCollection = slurpedDb.getCollection(name);
        for (DBObject item : slurpedCollection.find(update, findKeys)) {
          addToStream(operation, currentTimestamp, item, collection);
        }
      }
    } else {
      DBCollection slurpedCollection = slurpedDb.getCollection(collection);
      for (DBObject item : slurpedCollection.find(update, findKeys)) {
        addToStream(operation, currentTimestamp, item, collection);
      }
    }
  }
  // Steps:
  // 1. Install unlimited strength encryption jar files in jre/lib/security
  // (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html)
  // 2. run kinit
  // 3. Set system properties, e.g.:
  //    -Djava.security.krb5.realm=10GEN.ME -Djavax.security.auth.useSubjectCredsOnly=false
  // -Djava.security.krb5.kdc=kdc.10gen.me
  // auth.login.defaultCallbackHandler=name of class that implements
  // javax.security.auth.callback.CallbackHandler
  // You may also need to define realms and domain_realm entries in your krb5.conf file (in /etc by
  // default)
  public static void main(String[] args) throws UnknownHostException, InterruptedException {
    // Set this property to avoid the default behavior where the program prompts on the command line
    // for username/password
    Security.setProperty("auth.login.defaultCallbackHandler", "DefaultSecurityCallbackHandler");

    String server = args[0];
    String user = args[1];
    String dbName = args[2];

    MongoClient mongo =
        new MongoClient(
            new MongoClientAuthority(
                new ServerAddress(server),
                new MongoClientCredentials(user, MongoClientCredentials.GSSAPI_MECHANISM)),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongo.getDB(dbName);
    System.out.println("Find     one: " + testDB.getCollection("test").findOne());
    System.out.println("Count: " + testDB.getCollection("test").count());
    WriteResult writeResult = testDB.getCollection("test").insert(new BasicDBObject());
    System.out.println("Write result: " + writeResult);

    System.out.println();

    System.out.println("Count: " + testDB.getCollection("test").count());
  }
 public void Practice3() {
   List<String> courselist = new ArrayList<String>();
   double id = 0;
   DBCollection dBCollection = db.getCollection("teacher");
   BasicDBObject query = new BasicDBObject("last_name", "rodriguez");
   BasicDBObject fields = new BasicDBObject("_id", 1);
   DBCursor cursor = dBCollection.find(query, fields);
   try {
     if (cursor.hasNext()) {
       id = (Double) cursor.next().get("_id");
     }
   } finally {
     cursor.close();
   }
   dBCollection = db.getCollection("course");
   query = new BasicDBObject("teacher", id);
   fields = new BasicDBObject("name", 1);
   cursor = dBCollection.find(query, fields);
   try {
     while (cursor.hasNext()) {
       courselist.add((String) cursor.next().get("name"));
     }
   } finally {
     cursor.close();
   }
   Collections.sort(courselist);
   for (int i = 0; i < courselist.size(); i++) {
     System.out.println(courselist.get(i));
   }
 }
 public void Practice2() {
   BasicDBObject note;
   BasicDBObject course_id;
   List<BasicDBObject> obj;
   List<Double> courselist = new ArrayList<Double>();
   DBCollection dBCollection = db.getCollection("course");
   BasicDBObject query = new BasicDBObject("name", "math");
   BasicDBObject fields = new BasicDBObject("_id", 1);
   DBCursor cursor = dBCollection.find(query, fields);
   try {
     while (cursor.hasNext()) {
       courselist.add((Double) cursor.next().get("_id"));
     }
   } finally {
     cursor.close();
   }
   dBCollection = db.getCollection("student");
   note = new BasicDBObject("final", new BasicDBObject("$gt", 4));
   for (int i = 0; i < courselist.size(); i++) {
     obj = new ArrayList<BasicDBObject>();
     obj.add(note);
     course_id = new BasicDBObject("course_id", courselist.get(i));
     obj.add(course_id);
     query = new BasicDBObject("$and", obj);
     fields = new BasicDBObject("last_name", 1);
     cursor = dBCollection.find(query, fields);
     try {
       while (cursor.hasNext()) {
         System.out.println(cursor.next().get("last_name"));
       }
     } finally {
       cursor.close();
     }
   }
 }
Example #8
0
  public static void main(String[] args) throws IOException {
    String term =
        JOptionPane.showInputDialog(
            "Welcome to our knock-off search engine! \nPlease enter a term to search:");
    while (term == null || term.isEmpty()) {
      term =
          JOptionPane.showInputDialog(
              "You didn't input anything! \nPlease enter a term to search: ");
    }
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    System.out.println("Establishing connection...");

    // Get the connection.
    DB db = mongoClient.getDB("crawler");
    DBCollection table = db.getCollection("urlpages");

    System.out.println("Connected to MongoDB!");
    db.getCollection("pagerank").drop();

    Ranking ranker = new Ranking(db);
    ranker.link_analysis();
    ranker.TFIDF(term);

    run(term, db);

    JOptionPane.showMessageDialog(
        null,
        "Search is completed! \nPlease refer to 'C:\\data\\search_results.json' for the result.");
  }
Example #9
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("in side servlet");
    PrintWriter out = response.getWriter();

    try {
      long time = System.currentTimeMillis() - 60000;
      DB db = CommonDB.getBankConnection();
      DB db1 = CommonDB.getConnection();
      DBCollection coll = db.getCollection("Regular");
      DBCollection coll1 = db1.getCollection("CISResponse");
      BasicDBObject objs = new BasicDBObject("response_time", new BasicDBObject("$gt", time));
      BasicDBObject objs1 = new BasicDBObject("exectime", new BasicDBObject("$gt", time));
      int webUserCount = coll1.distinct("IP_Address", objs1).size();
      /*
       * List cityList = coll.distinct("city", objs);
       * cityList.remove("GPS not available !!!");
       */
      int appUserCount = coll.distinct("UUID", objs).size();
      System.out.println("count is : " + webUserCount + appUserCount);
      out.print("{\"WebUserCount\":" + webUserCount + ",\"AppUserCount\":" + appUserCount + "}");

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
 @Override
 public void dropIndex(final DB db, final DBObject spec, final String collectionName) {
   List<DBObject> indexes = db.getCollection(collectionName).getIndexInfo();
   String indexName = (String) spec.get("index");
   if (doesNotExist(indexes, indexName)) {
     throw new DropIndexFailed("Cannot drop index : " + indexName + " Index doesn't exist.");
   }
   db.getCollection(collectionName).dropIndex(indexName);
 }
  public void run() throws UnknownHostException {
    final List<Integer> models = new ArrayList<Integer>();
    final List<String> owners = new ArrayList<String>();
    final MongoClient client = new MongoClient();

    DB db = client.getDB("mongo_hadoop");
    DBCollection devices = db.getCollection("devices");
    DBCollection logs = db.getCollection("logs");

    if ("true".equals(System.getenv("SENSOR_DROP"))) {
      LOG.info("Dropping sensor data");
      devices.drop();
      logs.drop();
      devices.createIndex(new BasicDBObject("devices", 1));
    }
    db.getCollection("logs_aggregate").createIndex(new BasicDBObject("devices", 1));

    if (logs.count() == 0) {
      for (int i = 0; i < 10; i++) {
        owners.add(getRandomString(10));
      }

      for (int i = 0; i < 10; i++) {
        models.add(getRandomInt(10, 20));
      }

      List<ObjectId> deviceIds = new ArrayList<ObjectId>();
      for (int i = 0; i < NUM_DEVICES; i++) {
        DBObject device =
            new BasicDBObject("_id", new ObjectId())
                .append("name", getRandomString(5) + getRandomInt(3, 5))
                .append("type", choose(TYPES))
                .append("owner", choose(owners))
                .append("model", choose(models))
                .append("created_at", randomDate(new Date(2000, 1, 1, 16, 49, 29), new Date()));
        deviceIds.add((ObjectId) device.get("_id"));
        devices.insert(device);
      }

      for (int i = 0; i < NUM_LOGS; i++) {
        if (i % 50000 == 0) {
          LOG.info(format("Creating %d sensor log data entries: %d%n", NUM_LOGS, i));
        }
        BasicDBList location = new BasicDBList();
        location.add(getRandomInRange(-180, 180, 3));
        location.add(getRandomInRange(-90, 90, 3));
        DBObject log =
            new BasicDBObject("_id", new ObjectId())
                .append("d_id", choose(deviceIds))
                .append("v", getRandomInt(0, 10000))
                .append("timestamp", randomDate(new Date(2013, 1, 1, 16, 49, 29), new Date()))
                .append("loc", location);
        logs.insert(log);
      }
    }
  }
Example #12
0
 Boolean Del_MailList(String Time) {
   try {
     SendMailColl = SendMailDB.getCollection("Mail_Content");
     SendMailColl.remove(new BasicDBObject().append("time", Time));
     SendMailColl = SendMailDB.getCollection(Time);
     SendMailColl.drop();
     return true;
   } catch (Exception e) {
     return false;
   }
 }
Example #13
0
 @Test
 public void testGetCollection() {
   Fongo fongo = newFongo();
   DB db = fongo.getDB("db");
   DBCollection collection = db.getCollection("coll");
   assertNotNull(collection);
   assertSame("getCollection should be idempotent", collection, db.getCollection("coll"));
   assertSame(
       "getCollection should be idempotent", collection, db.getCollectionFromString("coll"));
   assertEquals(new HashSet<String>(Arrays.asList("coll")), db.getCollectionNames());
 }
 @Override
 public void dropIndex(final DB db, final DBObject spec, final String collectionName) {
   List<DBObject> indexes = db.getCollection(collectionName).getIndexInfo();
   DBObject indexObj = (DBObject) spec.get("index");
   toMongoFormat(indexObj);
   if (doesNotExist(indexes, indexObj)) {
     throw new DropIndexFailed(
         "Cannot drop index : " + indexObj.toString() + " Index doesn't exist.");
   }
   db.getCollection(collectionName).dropIndex(indexObj);
 }
  @Test
  @Ignore("Really slow on the delete, not a good unit tests atm")
  public void deleteBatchTest() throws Exception {

    DB db = getDb();

    int count = (int) (OpDelete.BATCH_SIZE * 1.5);

    List<DBObject> docs = new ArrayList<DBObject>(count);

    for (int i = 0; i < count; i++) {
      BasicDBObject doc = new BasicDBObject();

      doc.put("index", i);

      docs.add(doc);
    }

    WriteResult result = db.getCollection("deletebatchtests").insert(docs);

    assertNull(result.getLastError().getErrorMessage());

    // iterate over all the data to make sure it's been inserted

    DBCursor cursor = db.getCollection("deletebatchtests").find();

    for (int i = 0; i < count && cursor.hasNext(); i++) {
      int index = new BasicDBObject(cursor.next().toMap()).getInt("index");

      assertEquals(i, index);
    }

    BasicDBObject query = new BasicDBObject();
    query.put("index", new BasicDBObject("$lte", count));

    // now delete the objects
    db.getCollection("deletebatchtests").remove(query, WriteConcern.SAFE);

    // now  try and iterate, there should be no results
    cursor = db.getCollection("deletebatchtests").find();

    assertFalse(cursor.hasNext());

    // check it has been deleted
    UUID appId = emf.lookupApplication("test-organization/test-app");
    EntityManager em = emf.getEntityManager(appId);

    Results results =
        em.searchCollection(
            new SimpleEntityRef("application", appId), "deletebatchtests", new Query());

    assertEquals(0, results.size());
  }
  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.");
  }
Example #17
0
 @Test
 public void testDropCollectionsFromGetCollectionNames() {
   Fongo fongo = newFongo();
   DB db = fongo.getDB("db");
   db.getCollection("coll1");
   db.getCollection("coll2");
   int dropCount = 0;
   for (String name : db.getCollectionNames()) {
     db.getCollection(name).drop();
     dropCount++;
   }
   assertEquals("should drop two collections", 2, dropCount);
 }
 public void modifyFavorites(
     String m_clientId, String msisdn, boolean add, boolean isHikeUser, DB userDB) {
   FAVORITE_STATE state = add ? FAVORITE_STATE.ADDED : FAVORITE_STATE.REMOVED;
   DBCollection collection = userDB.getCollection(HikeConstants.MONGO_USERS_COLLECTION);
   modifyFavorites(collection, m_clientId, msisdn, state);
   if (add) {
     collection =
         isHikeUser
             ? userDB.getCollection(HikeConstants.MONGO_USERS_COLLECTION)
             : userDB.getCollection(HikeConstants.MONGO_NON_HIKERS_COLLECTION);
     modifyFavorites(collection, msisdn, m_clientId, FAVORITE_STATE.PENDING);
   }
 }
  private DBCollection calculateCollection(Exchange exchange) throws Exception {
    // dynamic calculation is an option. In most cases it won't be used and we should not penalise
    // all users with running this
    // resolution logic on every Exchange if they won't be using this functionality at all
    if (!endpoint.isDynamicity()) {
      return endpoint.getDbCollection();
    }

    String dynamicDB = exchange.getIn().getHeader(MongoDbConstants.DATABASE, String.class);
    String dynamicCollection =
        exchange.getIn().getHeader(MongoDbConstants.COLLECTION, String.class);

    @SuppressWarnings("unchecked")
    List<DBObject> dynamicIndex =
        exchange.getIn().getHeader(MongoDbConstants.COLLECTION_INDEX, List.class);

    DBCollection dbCol = null;

    if (dynamicDB == null && dynamicCollection == null) {
      dbCol = endpoint.getDbCollection();
    } else {
      DB db = null;

      if (dynamicDB == null) {
        db = endpoint.getDb();
      } else {
        db = endpoint.getMongoConnection().getDB(dynamicDB);
      }

      if (dynamicCollection == null) {
        dbCol = db.getCollection(endpoint.getCollection());
      } else {
        dbCol = db.getCollection(dynamicCollection);

        // on the fly add index
        if (dynamicIndex == null) {
          endpoint.ensureIndex(dbCol, endpoint.createIndex());
        } else {
          endpoint.ensureIndex(dbCol, dynamicIndex);
        }
      }
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Dynamic database and/or collection selected: {}->{}",
          dbCol.getDB().getName(),
          dbCol.getName());
    }
    return dbCol;
  }
  // 删除指定id的语料
  public void deletecorpus() throws UnknownHostException {
    String message = "请输入要读取的文本编号!";
    long idm = 1;
    Object obj = JOptionPane.showInputDialog(null, message, idm);
    String obj1 = (String) obj;

    if (obj1 == null) {
      return;
    }
    long id1 = Long.parseLong(obj1);

    MongoClient mc = null;
    DB db = null;
    mc = new MongoClient("127.0.0.1", 27017);
    db = mc.getDB("corpus");
    DBCollection textsave = null;
    if (Readcorpustype == "熟语料") {
      textsave = db.getCollection("ripe");
    } else if (Readcorpustype == "生语料") {
      textsave = db.getCollection("raw");
    } else if (Readcorpustype == null) {
      JOptionPane.showMessageDialog(null, "请在帮助菜单中设置语料类型!");
      return;
    }
    DBCursor cursor = textsave.find();
    Gson gson = new Gson();
    long countoftextsave = textsave.getCount();
    long counti = 0;
    long uid = -1;
    while (cursor.hasNext()) {
      DBObject st = cursor.next();
      Savetext u = gson.fromJson(st.toString(), Savetext.class);
      counti++;
      uid = u.id;
      if (uid == id1) {
        ReadDbobject = cursor.curr();
        textsave.remove(ReadDbobject);
        System.out.println("删除成功");
        break;
      } else if (uid != id1) {
        continue;
      }
    }
    if ((counti == countoftextsave) && (uid != id1)) {
      JOptionPane.showMessageDialog(null, "wrong id!");
      return;
    }
  }
  @Test
  public void deleteTest() throws Exception {

    DB db = getDb();

    BasicDBObject doc = new BasicDBObject();

    doc.put("name", "nico");
    doc.put("color", "tabby");

    WriteResult result = db.getCollection("deletetests").insert(doc);

    ObjectId savedOid = doc.getObjectId("_id");

    assertNull(result.getError());

    BasicDBObject query = new BasicDBObject();
    query.put("_id", savedOid);

    // now load by the mongo Id. Users will use this the most to read data.

    BasicDBObject returnedObject =
        new BasicDBObject(db.getCollection("deletetests").findOne(query).toMap());

    assertEquals("nico", returnedObject.get("name"));
    assertEquals("tabby", returnedObject.get("color"));

    // TODO uncomment me assertEquals(savedOid,
    // returnedObject.getObjectId("_id"));

    UUID id = UUID.fromString(returnedObject.get("uuid").toString());

    // now delete the object
    db.getCollection("deletetests").remove(returnedObject, WriteConcern.SAFE);

    DBObject searched = db.getCollection("deletetests").findOne(query);

    assertNull(searched);

    // check it has been deleted

    UUID appId = emf.lookupApplication("test-organization/test-app");
    EntityManager em = emf.getEntityManager(appId);

    Entity entity = em.get(id);

    assertNull(entity);
  }
  public JsonArray updatePerfResults(String perfResults) {
    BasicDBObject doc = (BasicDBObject) JSON.parse(perfResults);
    doc.append("_id", doc.get("name"));

    DBCollection coll = db.getCollection("performance");
    BasicDBObject query = new BasicDBObject();

    query.put("_id", doc.get("name"));

    DBCursor cursor = coll.find(query);

    JsonObjectBuilder objBuild = Json.createObjectBuilder();
    JsonArrayBuilder arrBuild = Json.createArrayBuilder();
    JsonObject json = objBuild.build();

    if (cursor.count() > 0) {
      LOG.info("Performance Results Found and Updated: " + coll.update(query, doc, true, false));
      json = Json.createReader(new StringReader(perfResults)).readObject();
      return arrBuild.add(json).build();
    } else {
      LOG.info("Performance Results Created: " + coll.insert(doc));
      json = Json.createReader(new StringReader(perfResults)).readObject();
      return arrBuild.add(json).build();
    }
  }
  public JsonArray addPerfResults(String perfResults) {
    DBCollection coll = db.getCollection("performance");
    BasicDBObject newPerfResults = (BasicDBObject) JSON.parse(perfResults);
    newPerfResults.append("_id", newPerfResults.getString("name"));

    BasicDBObject query = new BasicDBObject();
    query.append("name", newPerfResults.getString("name"));

    BasicDBObject removeId = new BasicDBObject("_id", 0);
    DBCursor cursor = coll.find(query, removeId);

    JsonObjectBuilder objBuild = Json.createObjectBuilder();
    JsonArrayBuilder arrBuild = Json.createArrayBuilder();
    JsonObject json = objBuild.build();

    if (cursor.count() > 0) {
      LOG.info("Performance Results Found: ");
      BasicDBObject found = (BasicDBObject) cursor.next();
      json = Json.createReader(new StringReader(found.toString())).readObject();
      arrBuild.add(json);
    } else {
      LOG.info("New Performance Results Created: " + coll.insert(newPerfResults));
      json = Json.createReader(new StringReader(newPerfResults.toString())).readObject();
      arrBuild.add(json);
    }

    LOG.info(
        "----------------------------------- ARR BUILD -------------------------------------------------\n"
            + arrBuild.build().toString());

    return arrBuild.build();
  }
  public JsonArray getPerfResults(String perfResults) {
    DBCollection coll = db.getCollection("performance");
    BasicDBObject query = new BasicDBObject();
    BasicDBObject removeId = new BasicDBObject("_id", 0);

    query.put("name", perfResults);

    DBCursor cursor = coll.find(query, removeId);
    JsonObjectBuilder objBuild = Json.createObjectBuilder();
    JsonArrayBuilder arrBuild = Json.createArrayBuilder();
    JsonObject json = objBuild.build();

    while (cursor.hasNext()) {
      BasicDBObject found = (BasicDBObject) cursor.next();
      LOG.info("Found Performance Results: " + found.toString());
      json = Json.createReader(new StringReader(found.toString())).readObject();

      arrBuild.add(json);
    }

    LOG.info(
        "----------------------------------- ARR BUILD -------------------------------------------------\n"
            + arrBuild.build().toString());

    return arrBuild.build();
  }
Example #25
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 #26
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 #27
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";
  }
 @Override
 public DBObject findDocumentByObjectId(String collectionName, String objectId) {
   DBCollection dbCollection = db.getCollection(collectionName);
   BasicDBObject query = new BasicDBObject();
   query.put("_id", new ObjectId(objectId));
   return dbCollection.findOne(query);
 }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // response.getWriter().append("Served at: ").append(request.getContextPath());
    MongoClientURI uri =
        new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());
    DBCollection users = db.getCollection("UserRecords");
    BasicDBObject query = new BasicDBObject();

    String firstname = request.getParameter("FirstName");
    String lastname = request.getParameter("LastName");
    String email = request.getParameter("email");
    String password = request.getParameter("EnterPassword");
    String confpasswd = request.getParameter("ConfirmPassword");
    query.put("First Name", firstname);
    query.put("Last Name", lastname);
    query.put("Email", email);
    System.out.println(email);
    if (password == confpasswd) {
      query.put("Password", password);
    } else {

    }
    DBCursor docs = users.find(query);
    response.getWriter().write(docs.toArray().toString());

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println("Insert doget");
  }
 @Before
 public void init() throws IOException {
   action = new MethodMsgAction();
   MapPubSub pubSub = new MapPubSub();
   DB db = initMongoDB();
   collection = db.getCollection("customer");
   collection.drop();
   BasicDBObject basicDBObject = new BasicDBObject();
   basicDBObject.put("_id", "testid");
   basicDBObject.put("testField", "pippo");
   collection.insert(basicDBObject);
   action.addInvoker(
       new MongoDBMethodInvoker(
           db,
           pubSub,
           new IdGenerator() {
             @Override
             public String generateCollectionID(String randomSeed) {
               return "fixed";
             }
           }));
   mockSession = new MockSession();
   session = new DDPSession(mockSession);
   pubSub.sub(
       new Sub() {
         {
           setName("customer");
         }
       },
       session);
 }