Example #1
0
  ArrayList<Person> Load_GroupList(String G_Name) {
    ArrayList<Person> PersonList = new ArrayList<Person>();

    GroupColl = AdressDB.getCollection(G_Name);

    if (GroupColl.getCount() != 0) {
      DBCursor cur;

      cur = GroupColl.find();

      while (cur.hasNext()) {
        Person P_Temp = new Person();

        P_Temp.ObjectID = cur.next().get("_id").toString();
        P_Temp.Name = cur.curr().get("name").toString();
        P_Temp.Mail_Address = cur.curr().get("mail").toString();
        P_Temp.Phone = cur.curr().get("phone").toString();

        PersonList.add(P_Temp);
      }
    } else {
      System.out.println("그룹에 사람 없음");
    }
    return PersonList;
  }
  @Test
  public void flushSavesObject() throws Exception {
    writer.flush();

    final DBCollection instances = testDb.getCollection(SPEC_NAME);
    assertEquals(1, instances.getCount());
  }
Example #3
0
  // 0이 이하 1이 이상 두개다 날짜면 사이
  ArrayList<Send_Mail> Load_Mail_List(long day, long checkday) {
    DBCursor cur;
    SendMailColl = SendMailDB.getCollection("Mail_Content");

    System.out.println(SendMailColl.getCount());
    // 이하
    // cur = SendMailColl.find(new BasicDBObject().append("id", new
    // BasicDBObject((checkday == 0 ? "$lte" : "$gte"), day)));// <= 상혁이꺼
    if (checkday == 0) {
      cur =
          SendMailColl.find(
              new BasicDBObject().append("time", new BasicDBObject("$lte", day))); // <=
      return Add_Mail_List(cur);
    }
    // 이상
    else if (checkday == 1) {
      cur =
          SendMailColl.find(
              new BasicDBObject().append("time", new BasicDBObject("$gte", day))); // >=
      return Add_Mail_List(cur);
    }
    // 사이값
    else {
      BasicDBObject query = new BasicDBObject();
      query.append("time", new BasicDBObject("$gte", day));
      query.append("time", new BasicDBObject("$lte", checkday));
      cur = SendMailColl.find(query);
      return Add_Mail_List(cur);
    }
  }
  /**
   * Imports a JSON resource into a MongoDB collection.
   *
   * @param resource the JSON resource
   * @param db the MongoDB datastore
   * @param collection the collection to update
   * @param drop indicates if the existing collection must be dropped
   */
  private void mongoImport(URL resource, DB db, String collection, boolean drop) {
    // keep a reference to the collection
    DBCollection c = db.getCollection(collection);

    // drop the content quickly, note that indexes must be created again if
    // necessary.
    if (drop) c.drop();

    int count = 0; // used to count the line
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream()))) {
      String line = null; // used to store the line as a string
      while ((line = reader.readLine()) != null) {
        count++; // count the lines

        // skip empty lines and line with comments
        line = line.trim();
        if (line.length() != 0 && !line.startsWith("#")) {
          // parse line
          DBObject obj = (DBObject) JSON.parse(line);
          // insert object to database
          try {
            c.insert(obj);
          } catch (MongoException e) {
            LOG.log(Level.WARNING, "Mongo DB exception while importing line " + count, e);
          }
        }
      }
    } catch (IOException e) {
      LOG.log(Level.WARNING, "IO exception while importing resource", e);
    }
    LOG.log(
        Level.INFO,
        "Imported {0} objects from {1} lines in collection {2}",
        new Object[] {c.getCount(), count, collection});
  }
  @Test
  public void objectNotSavedUntilFlush() throws Exception {
    writer.writeField("number", 1023);
    writer.writeField("string", "testing");

    final DBCollection instances = testDb.getCollection(SPEC_NAME);
    assertEquals(0, instances.getCount());
  }
Example #6
0
 @Override
 @Deprecated
 public long countAll() {
   final DBObject query = getQueryObject();
   if (LOG.isTraceEnabled()) {
     LOG.trace("Executing count(" + dbColl.getName() + ") for query: " + query);
   }
   return dbColl.getCount(query);
 }
  @Test
  public void writeFields() throws Exception {
    // writer.writeObjectType(SPEC_NAME);
    writer.writeOid(RootOidDefault.deString(SPEC_NAME + ":" + "D01", new OidMarshaller()));
    writer.writeField("number", 1023);
    writer.writeField("string", "testing");
    writer.flush();

    final DBCollection instances = testDb.getCollection(SPEC_NAME);
    assertEquals(1, instances.getCount());
    final DBObject object = instances.findOne();
    assertEquals(SPEC_NAME + ":" + "D01", object.get("_oid"));
    assertEquals("1023", object.get("number"));
    assertEquals("testing", object.get("string"));
  }
  @Test
  public void serialNumberNotStored() throws Exception {
    // writer.writeId("D01");
    writer.writeOid(RootOidDefault.deString(SPEC_NAME + ":" + "D01", new OidMarshaller()));
    writer.flush();

    final DBCollection instances = testDb.getCollection(SPEC_NAME);
    assertEquals(1, instances.getCount());
    final DBObject object = instances.findOne();

    assertEquals(SPEC_NAME + ":" + "D01", object.get("_oid"));
    assertEquals("D01", object.get("_id"));

    assertEquals(2, object.keySet().size());
  }
  // 删除指定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;
    }
  }
  @Scheduled(cron = "${application.geoarea.replication}")
  public void replicate() {

    logger.info("Starting replication of geographical data from data core");

    DB db = mongo.getDB(mongoDatabaseName);
    DBCollection collection = db.getCollection("geographical_area");

    Set<String> loadedUris = new HashSet<>();

    // 0. remove all pre-existing INCOMING records created but never changed to ONLINE
    deleteByStatus(GeographicalAreaReplicationStatus.INCOMING);

    // 1. fetch all the resources from the data core and insert them with status "incoming" in the
    // cache
    try {
      // Since there is not admin user connected, is necessary to get its admin authorization object
      // in order to send the request
      portalSystemUserService.runAs(
          new Runnable() {
            @Override
            public void run() {
              String lastDCIdFetched = null;
              do {
                logger.debug("Fetching batches of areas");
                lastDCIdFetched = fetchBatches(collection, loadedUris, lastDCIdFetched);
              } while (lastDCIdFetched != null);
            }
          });

      // 2. delete all the "online" entries (they are replaced with the "incoming" ones)
      long deleteStart = System.currentTimeMillis();
      deleteByStatus(GeographicalAreaReplicationStatus.ONLINE);
      logger.debug("Deleted online data in {} ms", System.currentTimeMillis() - deleteStart);

      // 3. switch all "incoming" entries to "online"
      long switchStart = System.currentTimeMillis();
      this.switchToOnline();
      logger.debug("Switched to online in {} ms", System.currentTimeMillis() - switchStart);
      logger.info(
          "Finish replication of {} geographical records from data core", collection.getCount());
    } catch (RestClientException e) {
      logger.error("Error while updating the geo area cache", e);

      // "rollback" to avoid duplicates on search (currently NOT filtered by the Status)
      this.deleteByStatus(GeographicalAreaReplicationStatus.INCOMING);
    }
  }
Example #11
0
  public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient(new ServerAddress("taru.zeeses.com", 27017));
    DB database = client.getDB("test");
    DBCollection collection = database.getCollection("scheduler");
    logger.info(String.valueOf(collection.getCount()));

    try {
      // Grab the Scheduler instance from the Factory
      Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

      // and start it off
      scheduler.start();

      doSomething(scheduler);

      scheduler.shutdown();

    } catch (SchedulerException se) {
      se.printStackTrace();
    }
  }
Example #12
0
  ArrayList<User> Load_UserList() {
    ArrayList<User> User_List = new ArrayList<User>();
    UserColl = UserDB.getCollection("User");

    if (UserColl.getCount() != 0) {
      DBCursor cur;

      cur = UserColl.find();

      while (cur.hasNext()) {
        User U_Temp = new User();

        U_Temp.ID = cur.next().get("id").toString();
        U_Temp.PW = cur.curr().get("password").toString();
        U_Temp.Key = null;

        User_List.add(U_Temp);
      }
    }
    return User_List;
  }
  // 将数据存入mongodb
  public void saveToMongo() throws UnknownHostException {
    // 选择生语料库还是熟语料库
    String message = "请选择存入的语料类型!";
    String corpusType[] = {"熟语料", "生语料"};
    Object obj =
        JOptionPane.showInputDialog(
            null, message, "请选择", JOptionPane.INFORMATION_MESSAGE, null, corpusType, "熟语料");
    String corpustype = ((String) obj);

    MongoClient mongoClient = new MongoClient();
    DB corpus = mongoClient.getDB("corpus"); // 在mongo中的数据库名字	
    Gson gson = new Gson();
    DBCursor cursor;
    DBCollection collection = null;
    // long id;
    long count;
    if (id == 0) {
      if (corpustype == "生语料" || corpustype == "熟语料") {
        if (corpustype == "生语料") {
          collection = corpus.getCollection("raw");
        } else if (corpustype == "熟语料") {
          collection = corpus.getCollection("ripe");
        }
        cursor = collection.find();
        count = collection.getCount();
        if (count > 0) {
          long idd = 0;
          // 获取id中的最大值
          while (cursor.hasNext()) {
            DBObject st = cursor.next();
            Savetext u = gson.fromJson(st.toString(), Savetext.class);
            if (idd < u.id) {
              idd = u.id;
            }
          }
          id = idd + 1;
        } else {
          id = 1;
        }
        Savetext saveText1 = new Savetext();
        saveText1.setMetaData1(fileContent1);
        saveText1.setKeyword1(keywordList);
        saveText1.setKeySentence1(sentenceList);
        saveText1.setSummary1(summaryList);
        saveText1.setTermList1(termList);
        saveText1.TermListString1 = editorDockable1.text.getText();
        saveText1.setTermListString1(saveText1.TermListString1);
        saveText1.setTextID(id);
        // 转换成json字符串,再转换成DBObject对象
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(saveText1));
        // 插入数据库
        collection.insert(dbObject);
        JOptionPane.showMessageDialog(null, "保存成功");
      } else if (corpustype == null) {
        // JOptionPane.showMessageDialog(null, "请选择存入语料的类型!!");
        return;
      } else if (corpustype.equals("")) {
        JOptionPane.showMessageDialog(null, "请选择存入语料的类型!!");
        return;
      }
      id = 0;
      System.out.println(id);
    } else if (id != 0) {
      if (Readcorpustype.equals(corpustype)) {
        // 此处为在本类型语料中修改
        if (corpustype == "生语料") {
          collection = corpus.getCollection("raw");
        } else if (corpustype == "熟语料") {
          collection = corpus.getCollection("ripe");
        }
        Savetext saveText1 = new Savetext();
        saveText1.setMetaData1(fileContent1);
        saveText1.setKeyword1(keywordList);
        saveText1.setKeySentence1(sentenceList);
        saveText1.setSummary1(summaryList);
        saveText1.setTermList1(termList);
        saveText1.TermListString1 = editorDockable1.text.getText();
        saveText1.setTermListString1(saveText1.TermListString1);
        saveText1.setTextID(id);
        // 转换成json字符串,再转换成DBObject对象
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(saveText1));
        collection.update(ReadDbobject, dbObject);
        JOptionPane.showMessageDialog(null, "修改成功");
      } else {
        // 此处为向corpustype中添加一个一个新语料,并删除Readcorpustype中的此语料。
        if (corpustype == "生语料") {
          collection = corpus.getCollection("raw");
        } else if (corpustype == "熟语料") {
          collection = corpus.getCollection("ripe");
        }
        DBCollection collection1 = null;
        if (Readcorpustype == "生语料") {
          collection1 = corpus.getCollection("raw");
        } else if (Readcorpustype == "熟语料") {
          collection1 = corpus.getCollection("ripe");
        }
        cursor = collection.find();
        count = collection.getCount();
        if (count > 0) {
          long idd = 0;
          // 获取id中的最大值
          while (cursor.hasNext()) {
            DBObject st = cursor.next();
            Savetext u = gson.fromJson(st.toString(), Savetext.class);
            if (idd < u.id) {
              idd = u.id;
            }
          }
          id = idd + 1;
        } else {
          id = 1;
        }
        Savetext saveText1 = new Savetext();
        saveText1.setMetaData1(fileContent1);
        saveText1.setKeyword1(keywordList);
        saveText1.setKeySentence1(sentenceList);
        saveText1.setSummary1(summaryList);
        saveText1.setTermList1(termList);
        saveText1.TermListString1 = editorDockable1.text.getText();
        saveText1.setTermListString1(saveText1.TermListString1);
        saveText1.setTextID(id);
        // 转换成json字符串,再转换成DBObject对象
        DBObject dbObject = (DBObject) JSON.parse(gson.toJson(saveText1));
        collection.insert(dbObject);
        collection1.remove(ReadDbobject);
        JOptionPane.showMessageDialog(null, "保存成功");
      }
    }
  }
  // 根据id读取语料
  public void readMongo() throws UnknownHostException {
    // new XialaLiebiaoTest();
    String message = "请输入要读取的文本编号!";
    long idm = 1;
    Object obj = JOptionPane.showInputDialog(null, message, idm);
    String obj1 = (String) obj;

    if (obj1 == null) {
      return;
    }
    id = 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();
    // SimpleAttributeSet att=new SimpleAttributeSet();
    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 == id) {
        editorDockable1.text.setText(u.TermListString1);
        termList = u.TermList1;
        fileContent1 = u.MetaData1;
        keywordList = u.Keyword1;
        sentenceList = u.KeySentence1;
        summaryList = u.Summary1;
        TermListString1 = u.TermListString1;
        for (int i = 0; i < termList.size(); i++) {
          randomColor();
          setColorss(termList.get(i).toString(), new Color(r, g, b));
        }
        ReadDbobject = cursor.curr();
        break;
      } else if (uid != id) {
        continue;
      }
    }
    if ((counti == countoftextsave) && (uid != id)) {
      JOptionPane.showMessageDialog(null, "wrong id!");
      return;
    }
    System.out.println(countoftextsave);
    System.out.println(counti);
    System.out.println(ReadDbobject);
  }
Example #15
0
  public static void main(String[] args) {
    // Collection
    DBCollection coll = DBUtils.getCollection("testCollection");

    // for test,clear collection first.
    coll.drop();

    // insert
    BasicDBObject doc = new BasicDBObject();
    doc.put("name", "MongoDB");
    doc.put("type", "database");
    doc.put("count", 1);

    BasicDBObject info = new BasicDBObject();

    info.put("x", 203);
    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

    // select findOne
    DBObject myDoc = coll.findOne();

    DBUtils.showTitle("findOne");
    System.out.println(myDoc);

    // mutil insert
    for (int i = 0; i < 100; i++) {
      coll.insert(new BasicDBObject().append("i", i));
    }

    // counting
    DBUtils.showTitle("mutil insert");
    System.out.println(coll.getCount());

    DBUtils.showTitle("Using a Cursor to Get All the Documents");
    DBCursor cur = coll.find();

    while (cur.hasNext()) {
      System.out.println(cur.next());
    }

    DBUtils.showTitle("Getting A Single Document with A Query");
    BasicDBObject query = new BasicDBObject();

    query.put("i", 71);

    cur = coll.find(query);

    while (cur.hasNext()) {
      System.out.println(cur.next());
    }

    //
    query.clear();
    Map<String, Object> criteria = new HashMap<String, Object>();
    criteria.put("$ne", 30);
    criteria.put("$gt", 10);
    query.put("i", new BasicDBObject(criteria).append("$lte", 50));

    DBUtils.showTitle("Getting A Single Document with mutil Query ");
    cur = coll.find(query);

    while (cur.hasNext()) {
      System.out.println(cur.next());
    }

    DBUtils.showTitle("Getting A Set of Documents With a Query");
    query = new BasicDBObject();

    query.put("i", new BasicDBObject("$gt", 50)); // e.g. find all where i > 50

    cur = coll.find(query);

    while (cur.hasNext()) {
      System.out.println(cur.next());
    }
  }
Example #16
0
 @Override
 public long count(final CountOptions options) {
   return dbColl.getCount(getQueryObject(), options.getOptions());
 }
Example #17
0
 @Override
 public long count() {
   return dbColl.getCount(getQueryObject());
 }
Example #18
0
  public static void main(String[] args) {
    try {
      // connect to mongoDB, ip and port number
      Mongo mongo = new Mongo("127.0.0.1", 27017);

      // get database from MongoDB,
      // if database doesn't exists, mongoDB will create it automatically
      DB db = mongo.getDB("yourdb");

      // Getting A List Of Collections
      Set<String> collections = db.getCollectionNames();

      for (String s : collections) {
        System.out.println(s);
      }

      // Get collection from MongoDB, database named "yourDB"
      // if collection doesn't exists, mongoDB will create it automatically
      DBCollection collection = db.getCollection("yourCollection");

      // create a document to store key and value
      DBObject document = new BasicDBObject();
      document.put("id", 1001);
      document.put("msg", "hello world mongoDB in Java");

      // save it into collection named "yourCollection"
      collection.insert(document);

      // search query
      DBObject searchQuery = new BasicDBObject();
      searchQuery.put("id", 1001);

      // query it
      DBCursor cursor = collection.find(searchQuery);

      // loop over the cursor and display the retrieved result
      while (cursor.hasNext()) {
        System.out.println("Our collection after putting document here: " + cursor.next());
      }

      // Counting Documents in Collection
      System.out.println("Elements in collection " + collection.getCount());

      // update document (just replase exist - it is normal practise)
      DBObject updatedDocument = new BasicDBObject();
      updatedDocument.put("id", 1001);
      updatedDocument.put("msg", "hello world mongoDB in Java updated");
      collection.update(new BasicDBObject().append("id", 1001), updatedDocument);

      // query it
      DBCursor cursorAfterUpdate = collection.find(searchQuery);

      // loop over the cursor and display the retrieved result
      while (cursorAfterUpdate.hasNext()) {
        System.out.println("Our collection after update: " + cursorAfterUpdate.next());
      }

      // Counting Documents in Collection
      System.out.println("Elements in collection " + collection.getCount());

      // Map to object
      Message message = new Message();
      message.setId((Integer) document.get("id"));
      message.setMessage((String) document.get("msg"));

      System.out.println("Id putted in object: " + message.getId());
      System.out.println("Message putted in object: " + message.getMessage());

      // Remove document from collection
      DBObject doc = collection.findOne(); // get first document
      collection.remove(doc);

      // query it
      DBCursor cursorAfterDelete = collection.find(searchQuery);

      // loop over the cursor and display the retrieved result
      while (cursorAfterDelete.hasNext()) {
        System.out.println("Our collection after delete: " + cursorAfterDelete.next());
      }

      // Counting Documents in Collection
      System.out.println("Elements in collection " + collection.getCount());

      // Close connection to db
      mongo.close();

      System.out.println("Done");

    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (MongoException e) {
      e.printStackTrace();
    }
  }
Example #19
0
  public static void main(String[] args) throws UnknownHostException {

    MongoClient mongo = new MongoClient("10.66.218.46", 27017);
    DB db = mongo.getDB("mydb");

    Set<String> collectionNames = db.getCollectionNames();
    for (String s : collectionNames) {
      System.out.println(s);
    }

    DBCollection conn = db.getCollection("testCollection");

    conn.drop();

    BasicDBObject doc =
        new BasicDBObject()
            .append("name", "MongoDB")
            .append("type", "database")
            .append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    conn.insert(doc);

    DBObject myDoc = conn.findOne();

    System.out.println(myDoc);

    for (int i = 0; i < 100; i++) {
      conn.insert(new BasicDBObject().append("i", i));
    }
    System.out.println(
        "total # of documents after inserting 100 small ones (should be 101) " + conn.getCount());

    // now use a query to get 1 document out
    DBCursor cursor = conn.find();
    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next());
      }
    } finally {
      cursor.close();
    }

    // now use a range query to get a larger subset
    BasicDBObject query = new BasicDBObject("i", 71);
    cursor = conn.find(query);

    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next());
      }
    } finally {
      cursor.close();
    }

    // range query with multiple constraints
    query =
        new BasicDBObject(
            "i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30
    cursor = conn.find(query);
    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next());
      }
    } finally {
      cursor.close();
    }

    // now use a range query to get a larger subset
    query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cursor = conn.find(query);

    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next());
      }
    } finally {
      cursor.close();
    }

    // create an index on the "i" field
    conn.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

    // list the indexes on the collection
    List<DBObject> list = conn.getIndexInfo();
    for (DBObject o : list) {
      System.out.println(o);
    }

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();

    mongo.close();
  }