Search in sources :

Example 16 with Datastore

use of dev.morphia.Datastore in project morphia by mongodb.

the class Filters method expr.

/**
 * Allows use of aggregation expressions within the query language.
 *
 * @param expression the expression to evaluate
 * @return the filter
 * @query.filter $expr
 */
public static Filter expr(Expression expression) {
    return new Filter("$expr", null, expression) {

        @Override
        public void encode(Datastore datastore, BsonWriter writer, EncoderContext context) {
            writer.writeName("$expr");
            Expression value = getValue();
            if (value != null) {
                wrapExpression(datastore, writer, value, context);
            } else {
                writer.writeNull();
            }
        }

        @Override
        public Expression getValue() {
            return (Expression) super.getValue();
        }
    };
}
Also used : Datastore(dev.morphia.Datastore) EncoderContext(org.bson.codecs.EncoderContext) Expression(dev.morphia.aggregation.experimental.expressions.impls.Expression) ExpressionHelper.wrapExpression(dev.morphia.aggregation.experimental.codecs.ExpressionHelper.wrapExpression) BsonWriter(org.bson.BsonWriter)

Example 17 with Datastore

use of dev.morphia.Datastore in project morphia by mongodb.

the class LifecycleEncoder method encode.

@Override
public void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
    EntityModel model = getMorphiaCodec().getEntityModel();
    Datastore datastore = getMorphiaCodec().getDatastore();
    Document document = new Document();
    model.callLifecycleMethods(PrePersist.class, value, document, datastore);
    final DocumentWriter documentWriter = new DocumentWriter(datastore.getMapper(), document);
    super.encode(documentWriter, value, encoderContext);
    document = documentWriter.getDocument();
    model.callLifecycleMethods(PostPersist.class, value, document, datastore);
    getMorphiaCodec().getRegistry().get(Document.class).encode(writer, document, encoderContext);
}
Also used : Datastore(dev.morphia.Datastore) DocumentWriter(dev.morphia.mapping.codec.writer.DocumentWriter) Document(org.bson.Document)

Example 18 with Datastore

use of dev.morphia.Datastore in project morphia by mongodb.

the class TestQuery method testTailableCursors.

@Test
public void testTailableCursors() {
    getMapper().map(CappedPic.class);
    final Datastore ds = getDs();
    final Query<CappedPic> query = ds.find(CappedPic.class);
    getMapper().map(CappedPic.class);
    ds.ensureCaps();
    final List<CappedPic> found = new ArrayList<>();
    assertCapped(CappedPic.class, 1000, 1024 * 1024);
    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    assertEquals(query.count(), 0);
    ScheduledFuture<?> scheduledFuture = executorService.scheduleAtFixedRate(() -> ds.save(new CappedPic()), 0, 100, TimeUnit.MILLISECONDS);
    Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> getDs().find(CappedPic.class).count() > 0);
    final Iterator<CappedPic> tail = query.iterator(new FindOptions().cursorType(CursorType.Tailable));
    Awaitility.await().pollDelay(500, TimeUnit.MILLISECONDS).atMost(10, TimeUnit.SECONDS).until(() -> {
        if (tail.hasNext()) {
            found.add(tail.next());
        }
        return found.size() >= 10;
    });
    executorService.shutdownNow();
    assertTrue(found.size() >= 10);
    assertTrue(query.count() >= 10);
}
Also used : FindOptions(dev.morphia.query.FindOptions) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Datastore(dev.morphia.Datastore) ArrayList(java.util.ArrayList) Test(org.testng.annotations.Test)

Example 19 with Datastore

use of dev.morphia.Datastore in project morphia by mongodb.

the class Employee method main.

public static void main(String[] args) {
    final Datastore datastore = Morphia.createDatastore(MongoClients.create(), "morphia_example");
    // tell morphia where to find your classes
    // can be called multiple times with different packages or classes
    datastore.getMapper().mapPackage("dev.morphia.example");
    // create the Datastore connecting to the database running on the default port on the local host
    datastore.getDatabase().drop();
    datastore.ensureIndexes();
    final Employee elmer = new Employee("Elmer Fudd", 50000.0);
    datastore.save(elmer);
    final Employee daffy = new Employee("Daffy Duck", 40000.0);
    datastore.save(daffy);
    final Employee pepe = new Employee("Pepé Le Pew", 25000.0);
    datastore.save(pepe);
    elmer.getDirectReports().add(daffy);
    elmer.getDirectReports().add(pepe);
    datastore.save(elmer);
    Query<Employee> query = datastore.find(Employee.class);
    final long employees = query.count();
    assertEquals(employees, 3);
    long underpaid = datastore.find(Employee.class).filter(lte("salary", 30000)).count();
    assertEquals(underpaid, 1);
    final Query<Employee> underPaidQuery = datastore.find(Employee.class).filter(lte("salary", 30000));
    final UpdateResult results = underPaidQuery.update(inc("salary", 10000)).execute();
    assertEquals(results.getModifiedCount(), 1);
    datastore.find(Employee.class).filter(gt("salary", 100000)).findAndDelete();
}
Also used : Datastore(dev.morphia.Datastore) UpdateResult(com.mongodb.client.result.UpdateResult)

Example 20 with Datastore

use of dev.morphia.Datastore in project morphia by mongodb.

the class TestLegacyQuery method testKeyList.

@Test
public void testKeyList() {
    final Rectangle rect = new Rectangle(1000, 1);
    Rectangle rectangle = getDs().save(rect);
    assertEquals(rectangle.getId(), rect.getId());
    final FacebookUser fbUser1 = new FacebookUser(1, "scott");
    final FacebookUser fbUser2 = new FacebookUser(2, "tom");
    final FacebookUser fbUser3 = new FacebookUser(3, "oli");
    final FacebookUser fbUser4 = new FacebookUser(4, "frank");
    final List<FacebookUser> users = getDs().save(asList(fbUser1, fbUser2, fbUser3, fbUser4));
    assertEquals(fbUser1.getId(), 1);
    final List<Key<FacebookUser>> fbUserKeys = new ArrayList<>();
    for (FacebookUser user : users) {
        fbUserKeys.add(getMapper().getKey(user));
    }
    assertEquals(fbUser1.getId(), fbUserKeys.get(0).getId());
    assertEquals(fbUser2.getId(), fbUserKeys.get(1).getId());
    assertEquals(fbUser3.getId(), fbUserKeys.get(2).getId());
    assertEquals(fbUser4.getId(), fbUserKeys.get(3).getId());
    final Keys k1 = new Keys(getMapper().getKey(rectangle), fbUserKeys);
    final Keys keys = getDs().save(k1);
    assertEquals(k1.getId(), keys.getId());
    final Datastore datastore = getDs();
    final Keys k1Loaded = datastore.find(Keys.class).filter("_id", k1.getId()).first();
    for (Key<FacebookUser> key : k1Loaded.getUsers()) {
        assertNotNull(key.getId());
    }
    assertNotNull(k1Loaded.getRect().getId());
}
Also used : Datastore(dev.morphia.Datastore) Rectangle(dev.morphia.test.models.Rectangle) ArrayList(java.util.ArrayList) Key(dev.morphia.Key) Test(org.testng.annotations.Test)

Aggregations

Datastore (dev.morphia.Datastore)46 Test (org.testng.annotations.Test)38 Morphia.createDatastore (dev.morphia.Morphia.createDatastore)12 FindOptions (dev.morphia.query.FindOptions)12 ArrayList (java.util.ArrayList)9 Document (org.bson.Document)9 EntityModel (dev.morphia.mapping.codec.pojo.EntityModel)6 UpdateOptions (dev.morphia.UpdateOptions)5 UpdateResult (com.mongodb.client.result.UpdateResult)4 MapperOptions (dev.morphia.mapping.MapperOptions)4 ObjectId (org.bson.types.ObjectId)4 Mapper (dev.morphia.mapping.Mapper)3 DocumentWriter (dev.morphia.mapping.codec.writer.DocumentWriter)3 Circle (dev.morphia.test.models.Circle)3 Rectangle (dev.morphia.test.models.Rectangle)3 Versioned (dev.morphia.test.models.versioned.Versioned)3 Point (com.mongodb.client.model.geojson.Point)2 Position (com.mongodb.client.model.geojson.Position)2 DeleteOptions (dev.morphia.DeleteOptions)2 Key (dev.morphia.Key)2