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

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

    try {
      DBCursor cursor = c.find().batchSize(2); // setting to 1, actually sets to 2 (why, oh why?)
      cursor.next(); // creates real cursor on server.
      cursor.next();
      assertEquals(0, cursor.numGetMores());
      cursor.next();
      assertEquals(1, cursor.numGetMores());
      cursor.next();
      cursor.next();
      assertEquals(2, cursor.numGetMores());
      cursor.next();
      cursor.next();
      assertEquals(3, cursor.numGetMores());
      cursor.batchSize(20);
      cursor.next();
      cursor.next();
      cursor.next();
      assertEquals(4, cursor.numGetMores());
    } catch (IllegalStateException e) {
      assertNotNull(e); // there must be a better way to detect this.
    }
  }
Example #2
0
  /**
   * Given the _id of a JSFile, return the file.
   *
   * @param id _id of the file to find
   * @return The file, if found, otherwise null
   */
  JSFile getJSFile(String id) {

    if (id == null) return null;

    DBCollection f = getDB().getCollection("_files");
    return (JSFile) (f.find(new ObjectId(id)));
  }
  @Test
  public void testBatchWithLimit() {
    DBCollection c = _db.getCollection("batchWithLimit1");
    c.drop();

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

    assertEquals(50, c.find().limit(50).itcount());
    assertEquals(50, c.find().batchSize(5).limit(50).itcount());
  }
  @Test
  public void testLargeBatch() {
    DBCollection c = _db.getCollection("largeBatch1");
    c.drop();

    int total = 50000;
    int batch = 10000;
    for (int i = 0; i < total; i++) c.save(new BasicDBObject("x", i));

    DBCursor cursor = c.find().batchSize(batch);
    assertEquals(total, cursor.itcount());
    assertEquals(total / batch + 1, cursor.getSizes().size());
  }
  @Test(groups = {"basic"})
  public void testGetServerAddressQuery1() {

    final DBCollection c = _db.getCollection("getServerAddress");
    c.drop();

    // Insert some data.
    for (int i = 0; i < 10; i++) c.insert(new BasicDBObject("one", i));

    final DBCursor cur = c.find(new BasicDBObject("one", 9));
    cur.hasNext();
    assertNotNull(cur.getServerAddress());
  }
  @Test(groups = {"basic"})
  public void testOptions() {
    DBCollection c = _db.getCollection("test");
    DBCursor dbCursor = c.find();

    assertEquals(0, dbCursor.getOptions());
    dbCursor.setOptions(Bytes.QUERYOPTION_TAILABLE);
    assertEquals(Bytes.QUERYOPTION_TAILABLE, dbCursor.getOptions());
    dbCursor.addOption(Bytes.QUERYOPTION_SLAVEOK);
    assertEquals(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_SLAVEOK, dbCursor.getOptions());
    dbCursor.resetOptions();
    assertEquals(0, dbCursor.getOptions());
  }
  @Test(groups = {"basic"})
  public void testCount() {
    try {
      DBCollection c = _db.getCollection("test");
      c.drop();

      assertEquals(c.find().count(), 0);

      BasicDBObject obj = new BasicDBObject();
      obj.put("x", "foo");
      c.insert(obj);

      assertEquals(c.find().count(), 1);
    } catch (MongoException e) {
      assertTrue(false);
    }
  }
  @Test // (enabled = false)
  public void testTailableAwait()
      throws ExecutionException, TimeoutException, InterruptedException {
    DBCollection c = _db.getCollection("tail1");
    c.drop();
    _db.createCollection("tail1", new BasicDBObject("capped", true).append("size", 10000));
    for (int i = 0; i < 10; i++) {
      c.save(new BasicDBObject("x", i), WriteConcern.SAFE);
    }

    final DBCursor cur =
        c.find()
            .sort(new BasicDBObject("$natural", 1))
            .addOption(Bytes.QUERYOPTION_TAILABLE | Bytes.QUERYOPTION_AWAITDATA);
    Callable<Object> callable =
        new Callable<Object>() {
          @Override
          public Object call() throws Exception {
            try {
              // the following call will block on the last hasNext
              int i = 0;
              while (cur.hasNext()) {
                DBObject obj = cur.next();
                i++;
                if (i > 10) return obj.get("x");
              }

              return null;
            } catch (Throwable e) {
              return e;
            }
          }
        };

    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Object> future = es.submit(callable);

    Thread.sleep(5000);
    assertTrue(!future.isDone());

    // this doc should unblock thread
    c.save(new BasicDBObject("x", 10), WriteConcern.SAFE);
    Object retVal = future.get(5, TimeUnit.SECONDS);
    assertEquals(10, retVal);
  }
 @Test(groups = {"basic"})
 public void testSnapshot() {
   DBCollection c = _db.getCollection("snapshot1");
   c.drop();
   for (int i = 0; i < 100; i++) c.save(new BasicDBObject("x", i));
   assertEquals(100, c.find().count());
   assertEquals(100, c.find().toArray().size());
   assertEquals(100, c.find().snapshot().count());
   assertEquals(100, c.find().snapshot().toArray().size());
   assertEquals(100, c.find().snapshot().limit(50).count());
   assertEquals(50, c.find().snapshot().limit(50).toArray().size());
 }
  @Test // (enabled = false)
  public void testTailable() {
    DBCollection c = _db.getCollection("tail1");
    c.drop();
    _db.createCollection("tail1", new BasicDBObject("capped", true).append("size", 10000));
    for (int i = 0; i < 10; i++) {
      c.save(new BasicDBObject("x", i));
    }

    DBCursor cur =
        c.find().sort(new BasicDBObject("$natural", 1)).addOption(Bytes.QUERYOPTION_TAILABLE);

    while (cur.hasNext()) {
      cur.next();
      // do nothing...
    }

    assert (!cur.hasNext());
    c.save(new BasicDBObject("x", 12));
    assert (cur.hasNext());
    assertNotNull(cur.next());
    assert (!cur.hasNext());
  }
  @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);
  }
  @Test
  public void testUpsert() {
    DBCollection c = _db.getCollection("upsert1");
    c.drop();

    c.update(
        new BasicDBObject("page", "/"),
        new BasicDBObject("$inc", new BasicDBObject("count", 1)),
        true,
        false);
    c.update(
        new BasicDBObject("page", "/"),
        new BasicDBObject("$inc", new BasicDBObject("count", 1)),
        true,
        false);

    assertEquals(1, c.getCount());
    assertEquals(2, c.findOne().get("count"));
  }
Example #13
0
    public TaskWrite(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {

      try {
        synchronized (slave) {
          Calendar calener = Calendar.getInstance();
          Date d1 = calener.getTime();
          Date d2 = new Date(calener.getTime().getTime() - 5000);
          BasicDBObject b2 = new BasicDBObject();
          b2.put("$gte", d2);
          b2.put("$lte", d1);
          DBCursor cursor =
              coll.find(new BasicDBObject("_id", b2)).sort(new BasicDBObject("_id", -1)).limit(1);
          while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            Set set1 = map1.entrySet();
            Iterator it1 = set1.iterator();
            while (it1.hasNext()) {
              Map.Entry<String, Map<String, String>> entry =
                  (Map.Entry<String, Map<String, String>>) it1.next();
              Map<String, String> map2 = entry.getValue();
              for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
                Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
                String name = entry2.getKey().toString();
                String paramAddr = entry2.getValue().toString();
                int fun = (int) (Double.parseDouble(paramAddr));
                if (paramAddr.substring(0, 1).equals("4")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setInputRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                }
                if (paramAddr.substring(0, 1).equals("3")) {
                  double value = Double.parseDouble(dbo.get(name).toString());
                  double dmax = (Double) m_max.get(name);
                  double dmin = (Double) m_min.get(name);
                  double dValue = 0;
                  if (value > dmax || value < dmin) {
                    if (value >= 0) {
                      dValue = 32000 * (int) (value / dmax);
                    }
                    if (value < 0) {
                      dValue = -32000 * (int) (value / dmin);
                    }
                    // slave.getProcessImage(3).setHoldingRegister(fun % 10000, (short) dValue);
                  } else { /// 参数超限报警
                    JOptionPane.showMessageDialog(null, "参数超限");
                    slave.stop();
                  }
                  ;
                }
                if (paramAddr.substring(0, 1).equals("2")) {
                  String value = dbo.get(name).toString();
                  /// slave.getProcessImage(4).setInput(fun % 10000, Boolean.valueOf(value));
                }
                if (paramAddr.substring(0, 1).equals("1")) {
                  String value = dbo.get(name).toString();
                  // slave.getProcessImage(4).setCoil(fun % 10000, Boolean.valueOf(value));
                }
              }
            }
          }
        }
      } catch (Exception ex) {
      }
    }
Example #14
0
    public TaskRead(Map map1, Map m_max, Map m_min, DBCollection coll, ModbusSlaveSet slave) {
      try {
        //// 此处只要点击开始就能保存数据
        /// 方案:利用数据源发送单个布尔型变量(1,0)交替,链接成功,先判断是否链接成功,然后在保存数据
        synchronized (slave) {
          Map map = new HashMap();
          Set set1 = map1.entrySet();
          Iterator it1 = set1.iterator();
          while (it1.hasNext()) {
            Map.Entry<String, Map<String, String>> entry =
                (Map.Entry<String, Map<String, String>>) it1.next();
            Map<String, String> map2 = entry.getValue();
            for (Iterator it2 = map2.entrySet().iterator(); it2.hasNext(); ) {
              Map.Entry<String, String> entry2 = (Map.Entry<String, String>) it2.next();
              String name = entry2.getKey().toString();
              String paramAddr = entry2.getValue().toString();
              int fun = (int) (Double.parseDouble(paramAddr));
              if (paramAddr.substring(0, 1).equals("4")) {
                Short d4 = slave.getProcessImage(1).getInputRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;
                if (d4 >= 0) {
                  dValue = dmax * d4 / 32000;
                } else {
                  dValue = dmin * d4 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("3")) {
                Short d3 = slave.getProcessImage(1).getHoldingRegister(fun % 10000);
                double dmax = (Double) m_max.get(name);
                double dmin = (Double) m_min.get(name);
                double dValue = 0;

                if (d3 >= 0) {
                  dValue = dmax * d3 / 32000;
                } else {
                  dValue = dmin * d3 / (-32000);
                }
                map.put(name, dValue);
              }
              if (paramAddr.substring(0, 1).equals("2")) {
                map.put(name, slave.getProcessImage(2).getInput(fun % 10000));
              }
              if (paramAddr.substring(0, 1).equals("1")) {
                Boolean a = slave.getProcessImage(2).getCoil(fun % 10000 - 1);
                map.put(name, a);
              }
            }
          }

          Calendar calendar = Calendar.getInstance();
          Date dd = calendar.getTime();

          BasicDBObject doc = new BasicDBObject();
          doc.put("_id", dd);

          Set set = map.entrySet();
          Iterator it = set.iterator();
          while (it.hasNext()) {
            Map.Entry<String, String> entry1 = (Map.Entry<String, String>) it.next();
            doc.put(entry1.getKey(), entry1.getValue());
          }
          coll.insert(doc);
        }
      } catch (Exception ex) {
      }
    }
Example #15
0
  public void receiveData(
      String ip,
      String paramName,
      String paramNo,
      int paramBote,
      int paramLength,
      int parmParity,
      int parmStopBit,
      int parmDelay) {
    try {
      try {
        m = new Mongo(ip, 27017);
        db = m.getDB(paramName);
        // db.authenticate("test", "123".toCharArray());
      } catch (UnknownHostException ex) {
        ex.printStackTrace();
      } catch (MongoException e) {
        e.printStackTrace();
      }
      final DBCollection coll = db.getCollection("DATAIN");
      final DBCollection collout = db.getCollection("DATAOUT");
      DBCollection meta = db.getCollection("META");

      // 记录数据字段
      final Map map1 = new HashMap();
      final Map map2 = new HashMap();
      Map map00 = new HashMap();
      Map map01 = new HashMap();
      Map map02 = new HashMap();
      Map map03 = new HashMap();

      final Map m_ai_max = new HashMap();
      final Map m_ai_min = new HashMap();
      final Map m_ao_max = new HashMap();
      final Map m_ao_min = new HashMap();

      DBCursor cursor = meta.find();
      while (cursor.hasNext()) {
        // 记录数据类型
        DBObject dbo = cursor.next();
        String name = dbo.get("_id").toString();
        String type = dbo.get("type").toString();
        String addr = dbo.get("addr").toString();
        Double max = (Double) dbo.get("max");
        Double min = (Double) dbo.get("min");
        if (type.equals("AI")) {
          map00.put(name, addr);
          m_ai_max.put(name, max);
          m_ai_min.put(name, min);
        }
        if (type.equals("DI")) {
          map01.put(name, addr);
        }
        if (type.equals("AO")) {
          map02.put(name, addr);
        }
        if (type.equals("DO")) {
          map03.put(name, addr);
        }
      }
      map1.put("AI", map00);
      map1.put("DI", map01);

      map2.put("AO", map02);
      map2.put("DO", map03);

      SerialParameters params = new SerialParameters();
      params.setCommPortId(paramNo);
      params.setBaudRate(paramBote);
      params.setDataBits(paramLength);
      params.setParity(parmParity);
      params.setStopBits(parmStopBit);
      ModbusFactory modbusFactory = new ModbusFactory();
      slave = modbusFactory.createRtuSlave(params);

      slave.addProcessImage(getModscanProcessImage(1, map00, coll));
      slave.addProcessImage(getModscanProcessImage(2, map01, coll));
      slave.addProcessImage(getModscanProcessImage(3, map02, collout));
      slave.addProcessImage(getModscanProcessImage(4, map03, collout));
      new Thread(
              new Runnable() {
                public void run() {
                  try {
                    slave.start();
                    // JOptionPane.showMessageDialog(f, "通讯连接成功!");
                  } catch (ModbusInitException e) {
                    e.printStackTrace();
                  }
                }
              })
          .start();
      ScheduledExecutorService timerRead = Executors.newScheduledThreadPool(1);
      timerRead.scheduleAtFixedRate(
          new Runnable() {
            public void run() {
              new TaskRead(map1, m_ai_max, m_ai_min, coll, slave);
            }
          },
          500,
          parmDelay,
          TimeUnit.MILLISECONDS);
      ScheduledExecutorService timerWrite = Executors.newScheduledThreadPool(2);
      timerWrite.scheduleAtFixedRate(
          new Runnable() {
            public void run() {
              new TaskWrite(map2, m_ao_max, m_ao_min, collout, slave);
            }
          },
          500,
          parmDelay,
          TimeUnit.MILLISECONDS);
    } catch (Exception ex) {
    }
  }
  @Test
  public void testBig() {
    DBCollection c = _db.getCollection("big1");
    c.drop();

    String bigString;
    {
      StringBuilder buf = new StringBuilder(16000);
      for (int i = 0; i < 16000; i++) buf.append("x");
      bigString = buf.toString();
    }

    int numToInsert = (15 * 1024 * 1024) / bigString.length();

    for (int i = 0; i < numToInsert; i++)
      c.save(BasicDBObjectBuilder.start().add("x", i).add("s", bigString).get());

    assert (800 < numToInsert);

    assertEquals(numToInsert, c.find().count());
    assertEquals(numToInsert, c.find().toArray().size());
    assertEquals(numToInsert, c.find().limit(800).count());
    assertEquals(800, c.find().limit(800).toArray().size());

    // negative limit works like negative batchsize, for legacy reason
    int x = c.find().limit(-800).toArray().size();
    assertLess(x, 800);

    DBCursor a = c.find();
    assertEquals(numToInsert, a.itcount());

    DBCursor b = c.find().batchSize(10);
    assertEquals(numToInsert, b.itcount());
    assertEquals(10, b.getSizes().get(0).intValue());

    assertLess(a.numGetMores(), b.numGetMores());

    assertEquals(numToInsert, c.find().batchSize(2).itcount());
    assertEquals(numToInsert, c.find().batchSize(1).itcount());

    assertEquals(numToInsert, _count(c.find(null, null).skip(0).batchSize(5)));
    assertEquals(5, _count(c.find(null, null).skip(0).batchSize(-5)));
  }
  @Test
  public void testExplain() {
    DBCollection c = _db.getCollection("explain1");
    c.drop();

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

    DBObject q = BasicDBObjectBuilder.start().push("x").add("$gt", 50).get();

    assertEquals(49, c.find(q).count());
    assertEquals(49, c.find(q).itcount());
    assertEquals(49, c.find(q).toArray().size());
    assertEquals(49, c.find(q).itcount());
    assertEquals(20, c.find(q).limit(20).itcount());
    assertEquals(20, c.find(q).limit(-20).itcount());

    c.ensureIndex(new BasicDBObject("x", 1));

    assertEquals(49, c.find(q).count());
    assertEquals(49, c.find(q).toArray().size());
    assertEquals(49, c.find(q).itcount());
    assertEquals(20, c.find(q).limit(20).itcount());
    assertEquals(20, c.find(q).limit(-20).itcount());

    assertEquals(49, c.find(q).explain().get("n"));

    assertEquals(20, c.find(q).limit(20).explain().get("n"));
    assertEquals(20, c.find(q).limit(-20).explain().get("n"));
  }
  @Test
  public void testLimitAndBatchSize() {
    DBCollection c = _db.getCollection("LimitAndBatchSize");
    c.drop();

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

    DBObject q = BasicDBObjectBuilder.start().push("x").add("$lt", 200).get();

    DBCursor cur = c.find(q);
    assertEquals(0, cur.getCursorId());
    assertEquals(200, cur.itcount());

    cur = c.find(q).limit(50);
    assertEquals(0, cur.getCursorId());
    assertEquals(50, cur.itcount());

    cur = c.find(q).batchSize(50);
    assertEquals(0, cur.getCursorId());
    assertEquals(200, cur.itcount());

    cur = c.find(q).batchSize(100).limit(50);
    assertEquals(0, cur.getCursorId());
    assertEquals(50, cur.itcount());

    cur = c.find(q).batchSize(-40);
    assertEquals(0, cur.getCursorId());
    assertEquals(40, cur.itcount());

    cur = c.find(q).limit(-100);
    assertEquals(0, cur.getCursorId());
    assertEquals(100, cur.itcount());

    cur = c.find(q).batchSize(-40).limit(20);
    assertEquals(0, cur.getCursorId());
    assertEquals(20, cur.itcount());

    cur = c.find(q).batchSize(-20).limit(100);
    assertEquals(0, cur.getCursorId());
    assertEquals(20, cur.itcount());
  }