├── .dockerignore ├── .github └── workflows │ ├── stale.yml │ └── test.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── pom.xml └── src ├── main └── java │ └── org │ └── jongo │ ├── Aggregate.java │ ├── Command.java │ ├── Distinct.java │ ├── Find.java │ ├── FindAndModify.java │ ├── FindOne.java │ ├── Insert.java │ ├── Jongo.java │ ├── Mapper.java │ ├── MongoCollection.java │ ├── MongoCursor.java │ ├── ObjectIdUpdater.java │ ├── Oid.java │ ├── QueryModifier.java │ ├── RawResultHandler.java │ ├── ReflectiveObjectIdUpdater.java │ ├── ResultHandler.java │ ├── ResultHandlerFactory.java │ ├── Update.java │ ├── bson │ ├── Bson.java │ ├── BsonDBDecoder.java │ ├── BsonDBEncoder.java │ ├── BsonDBObject.java │ ├── BsonDocument.java │ ├── BufferedBsonDocument.java │ ├── LazyBsonDocument.java │ └── Primitives.java │ ├── marshall │ ├── Marshaller.java │ ├── MarshallingException.java │ ├── Unmarshaller.java │ └── jackson │ │ ├── IdSelector.java │ │ ├── JacksonEngine.java │ │ ├── JacksonIdFieldSelector.java │ │ ├── JacksonMapper.java │ │ ├── JacksonObjectIdUpdater.java │ │ ├── JongoAnnotationIntrospector.java │ │ ├── bson4jackson │ │ ├── BsonDeserializers.java │ │ ├── BsonModule.java │ │ ├── BsonSerializers.java │ │ ├── MongoBsonFactory.java │ │ ├── MongoBsonGenerator.java │ │ └── MongoBsonParser.java │ │ ├── configuration │ │ ├── AbstractMappingBuilder.java │ │ ├── AnnotationModifier.java │ │ ├── DefaultReaderCallback.java │ │ ├── DefaultWriterCallback.java │ │ ├── DeserializationFeatureModifier.java │ │ ├── MapperFeatureModifier.java │ │ ├── MapperModifier.java │ │ ├── Mapping.java │ │ ├── PropertyModifier.java │ │ ├── ReaderCallback.java │ │ ├── SerializationFeatureModifier.java │ │ ├── ViewReaderCallback.java │ │ ├── ViewWriterCallback.java │ │ ├── VisibilityModifier.java │ │ └── WriterCallback.java │ │ └── oid │ │ ├── Id.java │ │ ├── MongoId.java │ │ ├── MongoObjectId.java │ │ ├── ObjectId.java │ │ ├── ObjectIdDeserializer.java │ │ └── ObjectIdSerializer.java │ └── query │ ├── BsonQueryFactory.java │ ├── BsonSpecialChar.java │ ├── Context.java │ ├── Query.java │ ├── QueryFactory.java │ └── Stack.java └── test ├── java └── org │ └── jongo │ ├── AggregateTest.java │ ├── AlreadyCheckDBObjectTest.java │ ├── AnnotationsMisusedTest.java │ ├── BinaryTest.java │ ├── CommandTest.java │ ├── CountTest.java │ ├── DeprecatedAnnotationsCompatibilitySuiteTest.java │ ├── DistinctTest.java │ ├── FindAndModifyTest.java │ ├── FindOneTest.java │ ├── FindPartialFieldTest.java │ ├── FindSkipSortLimitTest.java │ ├── FindTest.java │ ├── FindWithModifierTest.java │ ├── FindWithResultMapperTest.java │ ├── GridFsTest.java │ ├── InsertTest.java │ ├── JacksonAnnotationsHandlingTest.java │ ├── JongoTest.java │ ├── MongoCollectionTest.java │ ├── MongoCursorTest.java │ ├── NestedPolymorphismTest.java │ ├── NonPojoTest.java │ ├── PolymorphismTest.java │ ├── ReflectiveObjectIdUpdaterTest.java │ ├── RemoveTest.java │ ├── SaveTest.java │ ├── UpdateTest.java │ ├── WriteConcernTest.java │ ├── bench │ ├── BenchUtil.java │ ├── DecoderBench.java │ ├── EncoderBench.java │ ├── FindBench.java │ ├── SaveBench.java │ └── YourkitBench.java │ ├── bson │ ├── BsonDBEncoderTest.java │ ├── LazyBsonDocumentTest.java │ └── PrimitivesTest.java │ ├── marshall │ ├── DocumentMarshallingTest.java │ ├── ParameterQueryBindingTest.java │ └── jackson │ │ ├── IdSpecTest.java │ │ ├── JacksonEngineTest.java │ │ ├── JacksonIdFieldSelectorTest.java │ │ ├── JacksonMapperTest.java │ │ ├── JacksonMixinTest.java │ │ ├── JacksonViewTest.java │ │ ├── ParameterBindingWithJacksonTest.java │ │ ├── UnmarshallingWithJsonCreatorTest.java │ │ ├── configuration │ │ └── MappingTest.java │ │ └── oid │ │ └── AnnotationsTest.java │ ├── model │ ├── Animal.java │ ├── Article.java │ ├── Coordinate.java │ ├── ExposableFriend.java │ ├── ExternalFriend.java │ ├── Fox.java │ ├── Friend.java │ ├── Gender.java │ ├── IdSpecSet.java │ ├── LinkedFriend.java │ ├── MapReduceData.java │ ├── TypeWithNested.java │ └── Views.java │ ├── query │ ├── BsonQueryFactoryTest.java │ └── QueryTest.java │ ├── spike │ ├── MarshallingListener.java │ ├── MongoDumpTest.java │ ├── QuestionsSpikeTest.java │ └── projection │ │ ├── JacksonProjection.java │ │ ├── JacksonProjectionTest.java │ │ └── Projection.java │ └── util │ ├── BsonUtil.java │ ├── ErrorObject.java │ ├── IdResultHandler.java │ ├── JongoTestBase.java │ ├── MongoEmbeddedRule.java │ ├── MongoResource.java │ ├── RandomPortNumberGenerator.java │ └── compatibility │ ├── CompatibilitySuite.java │ └── TestContext.java ├── resources └── 1000friends.bson └── sh ├── compatibility ├── jackson-versions-tests.sh └── mongodb-versions-tests.sh └── test.sh /.dockerignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .idea/ -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: 'Close stale issues and PRs' 2 | on: 3 | schedule: 4 | - cron: '0 2 * * *' 5 | jobs: 6 | stale: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/stale@v3 10 | with: 11 | stale-issue-label: 'stale' 12 | days-before-issue-stale: 60 13 | days-before-issue-close: 30 14 | exempt-pr-labels: 'work-in-progress' 15 | stale-issue-message: > 16 | This issue has been automatically marked as stale because it has not had 17 | recent activity. It will be closed if no further activity occurs. Thank you 18 | for your contributions. 19 | stale-pr-label: 'stale' 20 | days-before-pr-stale: 60 21 | days-before-pr-close: 30 22 | stale-pr-message: > 23 | This pull request has been automatically marked as stale because it has not had 24 | recent activity. It will be closed if no further activity occurs. Thank you 25 | for your contributions. 26 | 27 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [ push ] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - name: Set up JDK 1.8 9 | uses: actions/setup-java@v1 10 | with: 11 | java-version: 1.8 12 | - name: Run tests 13 | run: mvn --batch-mode --update-snapshots verify 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target/ 3 | *.iml 4 | *.ipr 5 | *.iws 6 | .project 7 | .classpath 8 | .settings/ 9 | node_modules/ 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Jongo logo 2 | 3 | ### Jongo, Query in Java as in Mongo shell 4 | 5 | ![ci](https://github.com/bguerout/jongo/actions/workflows/test.yml/badge.svg?branch=releases/1.5.x) 6 | [![codecov](https://codecov.io/gh/bguerout/jongo/branch/master/graph/badge.svg?token=x5SRoEqidT)](https://codecov.io/gh/bguerout/jongo) 7 | 8 | **Faithful spirit**, Mongo query language isn't available in Java, Jongo fixes that. Copy/paste your queries to string. 9 | 10 | **Object oriented**, Save & find objects into & from collections. Use embedded Jackson marshalling or your own. 11 | 12 | **Wood solid**, As fast as Mongo Java driver. Open source, fully tested & made of rock solid libraries. 13 | 14 | 15 | ```xml 16 | 17 | org.jongo 18 | jongo 19 | [1.5.0,) 20 | 21 | ``` 22 | 23 | Documentation available at jongo.org 24 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/Command.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | 20 | import com.mongodb.CommandResult; 21 | import com.mongodb.DB; 22 | import com.mongodb.DBObject; 23 | import org.jongo.marshall.Unmarshaller; 24 | import org.jongo.query.Query; 25 | import org.jongo.query.QueryFactory; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | import static org.jongo.ResultHandlerFactory.newResultHandler; 31 | 32 | public class Command { 33 | 34 | private final DB db; 35 | private final Unmarshaller unmarshaller; 36 | private Query query; 37 | private boolean throwOnError; 38 | 39 | public Command(DB db, Unmarshaller unmarshaller, QueryFactory queryFactory, String query, Object... parameters) { 40 | this.db = db; 41 | this.unmarshaller = unmarshaller; 42 | this.query = queryFactory.createQuery(query, parameters); 43 | } 44 | 45 | public Command throwOnError() { 46 | throwOnError = true; 47 | return this; 48 | } 49 | 50 | public ResultCommand field(String fieldName) { 51 | return new ResultCommand(fieldName); 52 | } 53 | 54 | public T as(final Class clazz) { 55 | return map(newResultHandler(clazz, unmarshaller)); 56 | } 57 | 58 | public T map(ResultHandler resultHandler) { 59 | CommandResult commandResult = executeCommand(); 60 | return resultHandler.map(commandResult); 61 | } 62 | 63 | private CommandResult executeCommand() { 64 | CommandResult commandResult = db.command(query.toDBObject()); 65 | if (throwOnError) { 66 | commandResult.throwOnError(); 67 | } 68 | return commandResult; 69 | } 70 | 71 | public class ResultCommand { 72 | 73 | private String fieldName; 74 | 75 | public ResultCommand(String fieldName) { 76 | this.fieldName = fieldName; 77 | } 78 | 79 | public List as(final Class clazz) { 80 | return map(newResultHandler(clazz, unmarshaller)); 81 | } 82 | 83 | public List map(ResultHandler resultHandler) { 84 | CommandResult commandResult = executeCommand(); 85 | List results = (List) commandResult.get(fieldName); 86 | if (results == null) { 87 | return new ArrayList(); 88 | } 89 | List mappedResult = new ArrayList(results.size()); 90 | for (DBObject dbObject : results) { 91 | mappedResult.add(resultHandler.map(dbObject)); 92 | } 93 | return mappedResult; 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/Distinct.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.BasicDBObject; 20 | import com.mongodb.DBCollection; 21 | import com.mongodb.DBObject; 22 | import org.jongo.marshall.Unmarshaller; 23 | import org.jongo.query.Query; 24 | import org.jongo.query.QueryFactory; 25 | 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | import static org.jongo.ResultHandlerFactory.newResultHandler; 30 | 31 | public class Distinct { 32 | private final DBCollection dbCollection; 33 | private final Unmarshaller unmarshaller; 34 | private final String key; 35 | private Query query; 36 | private final QueryFactory queryFactory; 37 | 38 | Distinct(DBCollection dbCollection, Unmarshaller unmarshaller, QueryFactory queryFactory, String key) { 39 | this.dbCollection = dbCollection; 40 | this.unmarshaller = unmarshaller; 41 | this.key = key; 42 | this.queryFactory = queryFactory; 43 | this.query = this.queryFactory.createQuery("{}"); 44 | } 45 | 46 | public Distinct query(String query) { 47 | this.query = queryFactory.createQuery(query); 48 | return this; 49 | } 50 | 51 | public Distinct query(String query, Object... parameters) { 52 | this.query = queryFactory.createQuery(query, parameters); 53 | return this; 54 | } 55 | 56 | @SuppressWarnings("unchecked") 57 | public List as(final Class clazz) { 58 | DBObject ref = query.toDBObject(); 59 | List distinct = dbCollection.distinct(key, ref); 60 | 61 | if (distinct.isEmpty() || resultsAreBSONPrimitive(distinct)) 62 | return (List) distinct; 63 | else { 64 | return typedList((List) distinct, newResultHandler(clazz, unmarshaller)); 65 | } 66 | } 67 | 68 | public List map(ResultHandler resultHandler) { 69 | DBObject ref = query.toDBObject(); 70 | List distinct = dbCollection.distinct(key, ref); 71 | 72 | if (distinct.isEmpty() || resultsAreBSONPrimitive(distinct)) { 73 | return typedList(asDBObjectList(distinct), resultHandler); 74 | } else { 75 | return typedList((List) distinct, resultHandler); 76 | } 77 | } 78 | 79 | private List asDBObjectList(List distinct) { 80 | List objects = new ArrayList(); 81 | for (Object object : distinct) { 82 | objects.add(new BasicDBObject(key, object)); 83 | } 84 | return objects; 85 | } 86 | 87 | private boolean resultsAreBSONPrimitive(List distinct) { 88 | return !(distinct.get(0) instanceof DBObject); 89 | } 90 | 91 | private List typedList(List distinct, ResultHandler handler) { 92 | List results = new ArrayList(); 93 | for (DBObject dbObject : distinct) { 94 | results.add(handler.map(dbObject)); 95 | } 96 | return results; 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/FindAndModify.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCollection; 20 | import com.mongodb.DBObject; 21 | import org.jongo.marshall.Unmarshaller; 22 | import org.jongo.query.Query; 23 | import org.jongo.query.QueryFactory; 24 | 25 | import static org.jongo.ResultHandlerFactory.newResultHandler; 26 | 27 | public class FindAndModify { 28 | 29 | private final DBCollection collection; 30 | private final Unmarshaller unmarshaller; 31 | private final QueryFactory queryFactory; 32 | private final Query query; 33 | private Query fields, sort, modifier; 34 | private boolean remove = false; 35 | private boolean returnNew = false; 36 | private boolean upsert = false; 37 | 38 | FindAndModify(DBCollection collection, Unmarshaller unmarshaller, QueryFactory queryFactory, String query, Object... parameters) { 39 | this.unmarshaller = unmarshaller; 40 | this.collection = collection; 41 | this.queryFactory = queryFactory; 42 | this.query = this.queryFactory.createQuery(query, parameters); 43 | } 44 | 45 | public FindAndModify with(String modifier, Object... parameters) { 46 | if (modifier == null) throw new IllegalArgumentException("Modifier may not be null"); 47 | this.modifier = queryFactory.createQuery(modifier, parameters); 48 | return this; 49 | } 50 | 51 | public T as(final Class clazz) { 52 | return map(newResultHandler(clazz, unmarshaller)); 53 | } 54 | 55 | public T map(ResultHandler resultHandler) { 56 | DBObject result = collection.findAndModify(query.toDBObject(), 57 | getAsDBObject(fields), 58 | getAsDBObject(sort), 59 | remove, 60 | getAsDBObject(modifier), 61 | returnNew, 62 | upsert); 63 | 64 | return result == null ? null : resultHandler.map(result); 65 | } 66 | 67 | public FindAndModify projection(String fields) { 68 | this.fields = queryFactory.createQuery(fields); 69 | return this; 70 | } 71 | 72 | public FindAndModify projection(String fields, Object... parameters) { 73 | this.fields = queryFactory.createQuery(fields, parameters); 74 | return this; 75 | } 76 | 77 | public FindAndModify sort(String sort) { 78 | this.sort = queryFactory.createQuery(sort); 79 | return this; 80 | } 81 | 82 | public FindAndModify remove() { 83 | this.remove = true; 84 | return this; 85 | } 86 | 87 | public FindAndModify returnNew() { 88 | this.returnNew = true; 89 | return this; 90 | } 91 | 92 | public FindAndModify upsert() { 93 | this.upsert = true; 94 | return this; 95 | } 96 | 97 | private DBObject getAsDBObject(Query query) { 98 | return query == null ? null : query.toDBObject(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/FindOne.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCollection; 20 | import com.mongodb.DBObject; 21 | import com.mongodb.ReadPreference; 22 | import org.jongo.marshall.Unmarshaller; 23 | import org.jongo.query.Query; 24 | import org.jongo.query.QueryFactory; 25 | 26 | import static org.jongo.ResultHandlerFactory.newResultHandler; 27 | 28 | public class FindOne { 29 | 30 | private final Unmarshaller unmarshaller; 31 | private final DBCollection collection; 32 | private final ReadPreference readPreference; 33 | private final Query query; 34 | private Query fields, orderBy; 35 | private final QueryFactory queryFactory; 36 | 37 | FindOne(DBCollection collection, ReadPreference readPreference, Unmarshaller unmarshaller, QueryFactory queryFactory, String query, Object... parameters) { 38 | this.unmarshaller = unmarshaller; 39 | this.collection = collection; 40 | this.readPreference = readPreference; 41 | this.queryFactory = queryFactory; 42 | this.query = this.queryFactory.createQuery(query, parameters); 43 | } 44 | 45 | public T as(final Class clazz) { 46 | return map(newResultHandler(clazz, unmarshaller)); 47 | } 48 | 49 | public T map(ResultHandler resultHandler) { 50 | DBObject result = collection.findOne(query.toDBObject(), getFieldsAsDBObject(), getOrderByAsDBObject(), readPreference); 51 | return result == null ? null : resultHandler.map(result); 52 | } 53 | 54 | public FindOne projection(String fields) { 55 | this.fields = queryFactory.createQuery(fields); 56 | return this; 57 | } 58 | 59 | public FindOne projection(String fields, Object... parameters) { 60 | this.fields = queryFactory.createQuery(fields, parameters); 61 | return this; 62 | } 63 | 64 | public FindOne orderBy(String orderBy) { 65 | this.orderBy = queryFactory.createQuery(orderBy); 66 | return this; 67 | } 68 | 69 | private DBObject getFieldsAsDBObject() { 70 | return fields == null ? null : fields.toDBObject(); 71 | } 72 | 73 | private DBObject getOrderByAsDBObject() { 74 | return orderBy == null ? null : orderBy.toDBObject(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/Jongo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DB; 20 | import com.mongodb.DBCollection; 21 | import com.mongodb.client.MongoDatabase; 22 | import org.jongo.bson.BsonDBDecoder; 23 | import org.jongo.bson.BsonDBEncoder; 24 | import org.jongo.query.Query; 25 | 26 | import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper; 27 | 28 | public class Jongo { 29 | 30 | private final DB database; 31 | private final Mapper mapper; 32 | 33 | public Jongo(DB database) { 34 | this(database, jacksonMapper().build()); 35 | } 36 | 37 | public Jongo(DB database, Mapper mapper) { 38 | this.database = database; 39 | this.mapper = mapper; 40 | } 41 | 42 | public MongoCollection getCollection(String name) { 43 | DBCollection dbCollection = database.getCollection(name); 44 | dbCollection.setDBDecoderFactory(BsonDBDecoder.FACTORY); 45 | dbCollection.setDBEncoderFactory(BsonDBEncoder.FACTORY); 46 | dbCollection.setReadConcern(database.getReadConcern()); 47 | return new MongoCollection(dbCollection, mapper); 48 | } 49 | 50 | public DB getDatabase() { 51 | return database; 52 | } 53 | 54 | public Mapper getMapper() { 55 | return mapper; 56 | } 57 | 58 | public Query createQuery(String query, Object... parameters) { 59 | return mapper.getQueryFactory().createQuery(query, parameters); 60 | } 61 | 62 | public Command runCommand(String query) { 63 | return runCommand(query, new Object[0]); 64 | } 65 | 66 | public Command runCommand(String query, Object... parameters) { 67 | return new Command(database, mapper.getUnmarshaller(), mapper.getQueryFactory(), query, parameters); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/Mapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import org.jongo.marshall.Marshaller; 20 | import org.jongo.marshall.Unmarshaller; 21 | import org.jongo.query.QueryFactory; 22 | 23 | public interface Mapper { 24 | 25 | Marshaller getMarshaller(); 26 | 27 | Unmarshaller getUnmarshaller(); 28 | 29 | ObjectIdUpdater getObjectIdUpdater(); 30 | 31 | QueryFactory getQueryFactory(); 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/MongoCursor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCursor; 20 | import com.mongodb.DBObject; 21 | 22 | import java.io.Closeable; 23 | import java.io.IOException; 24 | import java.util.Iterator; 25 | import java.util.NoSuchElementException; 26 | 27 | public class MongoCursor implements Iterator, Iterable, Closeable { 28 | 29 | private final DBCursor cursor; 30 | private final ResultHandler resultHandler; 31 | 32 | public MongoCursor(DBCursor cursor, ResultHandler resultHandler) { 33 | this.cursor = cursor; 34 | this.resultHandler = resultHandler; 35 | } 36 | 37 | public boolean hasNext() { 38 | return cursor.hasNext(); 39 | } 40 | 41 | public E next() { 42 | if (!hasNext()) 43 | throw new NoSuchElementException(); 44 | 45 | DBObject dbObject = cursor.next(); 46 | return resultHandler.map(dbObject); 47 | } 48 | 49 | public void remove() { 50 | throw new UnsupportedOperationException("remove() method is not supported"); 51 | } 52 | 53 | public Iterator iterator() { 54 | return new MongoCursor(cursor.copy(), resultHandler); 55 | } 56 | 57 | public void close() throws IOException { 58 | cursor.close(); 59 | } 60 | 61 | public int count() { 62 | return cursor.count(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/ObjectIdUpdater.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import org.bson.types.ObjectId; 20 | 21 | public interface ObjectIdUpdater { 22 | 23 | boolean mustGenerateObjectId(Object pojo); 24 | 25 | Object getId(Object pojo); 26 | 27 | void setObjectId(Object target, ObjectId id); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/Oid.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import static org.jongo.MongoCollection.MONGO_QUERY_OID; 20 | 21 | public class Oid { 22 | 23 | public static String withOid(String id) { 24 | return "{_id: {" + MONGO_QUERY_OID + ":\"" + id + "\"}}"; 25 | } 26 | 27 | private Oid() { 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/QueryModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCursor; 20 | 21 | public interface QueryModifier { 22 | void modify(DBCursor cursor); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/RawResultHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBObject; 20 | 21 | public class RawResultHandler implements ResultHandler { 22 | 23 | private final Class clazz; 24 | 25 | public RawResultHandler(Class clazz) { 26 | this.clazz = clazz; 27 | } 28 | 29 | public RawResultHandler() { 30 | this((Class) DBObject.class); 31 | } 32 | 33 | public T map(DBObject result) { 34 | return clazz.cast(result); 35 | } 36 | 37 | public static RawResultHandler asRaw(Class clazz) { 38 | return new RawResultHandler(clazz); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/ResultHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBObject; 20 | 21 | public interface ResultHandler { 22 | T map(DBObject result); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/ResultHandlerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBObject; 20 | import org.jongo.bson.Bson; 21 | import org.jongo.bson.BsonDocument; 22 | import org.jongo.marshall.Unmarshaller; 23 | 24 | class ResultHandlerFactory { 25 | 26 | 27 | public static ResultHandler newResultHandler(final Class clazz, final Unmarshaller unmarshaller) { 28 | return new UnmarshallingResultHandler(unmarshaller, clazz); 29 | } 30 | 31 | private static class UnmarshallingResultHandler implements ResultHandler { 32 | 33 | private final Unmarshaller unmarshaller; 34 | private final Class clazz; 35 | 36 | public UnmarshallingResultHandler(Unmarshaller unmarshaller, Class clazz) { 37 | this.unmarshaller = unmarshaller; 38 | this.clazz = clazz; 39 | } 40 | 41 | public T map(DBObject result) { 42 | BsonDocument bsonDocument = Bson.createDocument(result); 43 | return unmarshaller.unmarshall(bsonDocument, clazz); 44 | } 45 | } 46 | 47 | private ResultHandlerFactory() { 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/Update.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.*; 20 | import org.bson.LazyBSONObject; 21 | import org.jongo.query.Query; 22 | import org.jongo.query.QueryFactory; 23 | 24 | public class Update { 25 | 26 | private final DBCollection collection; 27 | private final Query query; 28 | private final QueryFactory queryFactory; 29 | 30 | private WriteConcern writeConcern; 31 | private boolean upsert = false; 32 | private boolean multi = false; 33 | 34 | Update(DBCollection collection, WriteConcern writeConcern, QueryFactory queryFactory, String query, Object... parameters) { 35 | this.collection = collection; 36 | this.writeConcern = writeConcern; 37 | this.queryFactory = queryFactory; 38 | this.query = createQuery(query, parameters); 39 | } 40 | 41 | public WriteResult with(String modifier) { 42 | return with(modifier, new Object[0]); 43 | } 44 | 45 | public WriteResult with(String modifier, Object... parameters) { 46 | Query updateQuery = queryFactory.createQuery(modifier, parameters); 47 | return collection.update(this.query.toDBObject(), updateQuery.toDBObject(), upsert, multi, writeConcern); 48 | } 49 | 50 | public WriteResult with(Object pojo) { 51 | 52 | DBObject updateDbo = queryFactory.createQuery("{$set:#}", pojo).toDBObject(); 53 | removeIdField(updateDbo); 54 | return collection.update(this.query.toDBObject(), updateDbo, upsert, multi, writeConcern); 55 | } 56 | 57 | private void removeIdField(DBObject updateDbo) { 58 | DBObject pojoAsDbo = (DBObject) updateDbo.get("$set"); 59 | if (pojoAsDbo.containsField("_id")) { 60 | // Need to materialize lazy objects which are read only 61 | if (pojoAsDbo instanceof LazyBSONObject) { 62 | BasicDBObject expanded = new BasicDBObject(); 63 | expanded.putAll(pojoAsDbo); 64 | updateDbo.put("$set", expanded); 65 | pojoAsDbo = expanded; 66 | } 67 | pojoAsDbo.removeField("_id"); 68 | } 69 | } 70 | 71 | public Update upsert() { 72 | this.upsert = true; 73 | return this; 74 | } 75 | 76 | public Update multi() { 77 | this.multi = true; 78 | return this; 79 | } 80 | 81 | private Query createQuery(String query, Object[] parameters) { 82 | try { 83 | return this.queryFactory.createQuery(query, parameters); 84 | } catch (Exception e) { 85 | String message = String.format("Unable execute update operation using query %s", query); 86 | throw new IllegalArgumentException(message, e); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/Bson.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.DBObject; 20 | 21 | public class Bson { 22 | 23 | public static boolean isPrimitive(Object obj) { 24 | return Primitives.contains(obj.getClass()); 25 | } 26 | 27 | public static BsonDocument createDocument(DBObject dbo) { 28 | if (dbo instanceof BsonDocument) { 29 | return (BsonDocument) dbo; 30 | } 31 | return new BufferedBsonDocument(dbo); 32 | } 33 | 34 | public static BsonDocument createDocument(byte[] bytes) { 35 | return new LazyBsonDocument(bytes); 36 | } 37 | 38 | private Bson() { 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/BsonDBDecoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.*; 20 | import com.mongodb.gridfs.GridFSDBFile; 21 | 22 | import java.util.Iterator; 23 | 24 | public class BsonDBDecoder extends LazyDBDecoder implements DBDecoder { 25 | 26 | public final static DBDecoderFactory FACTORY = new BsonDBDecoderFactory(); 27 | 28 | private BsonDBDecoder() { 29 | } 30 | 31 | public DBCallback getDBCallback(DBCollection collection) { 32 | return new CollectionDBCallback(collection); 33 | } 34 | 35 | private static class BsonDBDecoderFactory implements DBDecoderFactory { 36 | 37 | public DBDecoder create() { 38 | return new BsonDBDecoder(); 39 | } 40 | } 41 | 42 | private static class CollectionDBCallback extends LazyDBCallback { 43 | 44 | private final DBCollection collection; 45 | 46 | public CollectionDBCallback(DBCollection collection) { 47 | super(collection); 48 | this.collection = collection; 49 | } 50 | 51 | @Override 52 | public Object createObject(byte[] data, int offset) { 53 | 54 | if (isGridFSCollection()) { 55 | return DefaultDBDecoder.FACTORY.create().decode(data, collection); 56 | } 57 | 58 | DBObject dbo = new BsonDBObject(data, offset); 59 | if (isDBRef(dbo)) { 60 | return new DBRef((String) dbo.get("$ref"), dbo.get("$id")); 61 | } 62 | return dbo; 63 | } 64 | 65 | private boolean isGridFSCollection() { 66 | return GridFSDBFile.class.equals(collection.getObjectClass()); 67 | } 68 | 69 | private boolean isDBRef(DBObject dbo) { 70 | Iterator iterator = dbo.keySet().iterator(); 71 | return iterator.hasNext() && iterator.next().equals("$ref") && iterator.hasNext() && iterator.next().equals("$id"); 72 | } 73 | 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/BsonDBEncoder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.*; 20 | import org.bson.BSONObject; 21 | import org.bson.io.OutputBuffer; 22 | 23 | import java.io.IOException; 24 | 25 | public class BsonDBEncoder implements DBEncoder { 26 | 27 | public final static DBEncoderFactory FACTORY = new BsonDBEncoderFactory(); 28 | 29 | private BsonDBEncoder() { 30 | } 31 | 32 | public int writeObject(final OutputBuffer buf, BSONObject o) { 33 | 34 | if (!(o instanceof LazyDBObject)) { 35 | return DefaultDBEncoder.FACTORY.create().writeObject(buf, o); 36 | } 37 | 38 | try { 39 | return ((LazyDBObject) o).pipe(buf); 40 | } catch (IOException e) { 41 | throw new MongoException("Exception serializing a LazyDBObject", e); 42 | } 43 | } 44 | 45 | private static class BsonDBEncoderFactory implements DBEncoderFactory { 46 | public DBEncoder create() { 47 | return new BsonDBEncoder(); 48 | } 49 | 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/BsonDBObject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.DBObject; 20 | import com.mongodb.LazyDBCallback; 21 | import com.mongodb.LazyDBObject; 22 | 23 | class BsonDBObject extends LazyDBObject implements BsonDocument { 24 | 25 | public BsonDBObject(byte[] data, int offset) { 26 | super(data, offset, new BsonCallback()); 27 | } 28 | 29 | public byte[] toByteArray() { 30 | return getBytes(); 31 | } 32 | 33 | public DBObject toDBObject() { 34 | return this; 35 | } 36 | 37 | public int getSize() { 38 | return getBSONSize(); 39 | } 40 | 41 | static class BsonCallback extends LazyDBCallback { 42 | 43 | public BsonCallback() { 44 | super(null); 45 | } 46 | 47 | @Override 48 | public Object createObject(byte[] bytes, int offset) { 49 | return new LazyDBObject(bytes, offset, new BsonCallback()); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/BsonDocument.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | 20 | import com.mongodb.DBObject; 21 | 22 | public interface BsonDocument { 23 | 24 | byte[] toByteArray(); 25 | 26 | DBObject toDBObject(); 27 | 28 | int getSize(); 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/BufferedBsonDocument.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.DBEncoder; 20 | import com.mongodb.DBObject; 21 | import com.mongodb.DefaultDBEncoder; 22 | import org.bson.BSONObject; 23 | import org.bson.io.BasicOutputBuffer; 24 | import org.bson.io.OutputBuffer; 25 | 26 | class BufferedBsonDocument implements BsonDocument { 27 | 28 | private final OutputBuffer buffer; 29 | private final DBObject dbo; 30 | 31 | BufferedBsonDocument(DBObject dbo) { 32 | this.buffer = new BasicOutputBuffer(); 33 | this.dbo = dbo; 34 | encode(this.dbo); 35 | } 36 | 37 | private void encode(BSONObject dbo) { 38 | DBEncoder dbEncoder = DefaultDBEncoder.FACTORY.create(); 39 | dbEncoder.writeObject(buffer, dbo); 40 | } 41 | 42 | public int getSize() { 43 | return buffer.size(); 44 | } 45 | 46 | public byte[] toByteArray() { 47 | return buffer.toByteArray(); 48 | } 49 | 50 | public DBObject toDBObject() { 51 | return dbo; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return dbo.toString(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/LazyBsonDocument.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.DBObject; 20 | 21 | import java.nio.ByteBuffer; 22 | import java.nio.ByteOrder; 23 | 24 | class LazyBsonDocument implements BsonDocument { 25 | 26 | private final byte[] bytes; 27 | 28 | LazyBsonDocument(byte[] bytes) { 29 | this.bytes = bytes; 30 | } 31 | 32 | public int getSize() { 33 | return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(0); 34 | } 35 | 36 | public byte[] toByteArray() { 37 | return bytes; 38 | } 39 | 40 | public DBObject toDBObject() { 41 | return new BsonDBObject(bytes, 0); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return toDBObject().toString(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/bson/Primitives.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.DBObject; 20 | import com.mongodb.DBRef; 21 | import org.bson.types.*; 22 | 23 | import java.util.Date; 24 | import java.util.HashSet; 25 | import java.util.Set; 26 | import java.util.UUID; 27 | import java.util.regex.Pattern; 28 | 29 | class Primitives { 30 | 31 | private static final Set> PRIMITIVES; 32 | 33 | static { 34 | PRIMITIVES = new HashSet>(); 35 | PRIMITIVES.add(String.class); 36 | PRIMITIVES.add(Number.class); 37 | PRIMITIVES.add(Boolean.class); 38 | PRIMITIVES.add(MinKey.class); 39 | PRIMITIVES.add(MaxKey.class); 40 | PRIMITIVES.add(ObjectId.class); 41 | PRIMITIVES.add(Pattern.class); 42 | PRIMITIVES.add(BSONTimestamp.class); 43 | PRIMITIVES.add(Date.class); 44 | PRIMITIVES.add(UUID.class); 45 | PRIMITIVES.add(Code.class); 46 | PRIMITIVES.add(DBObject.class); 47 | PRIMITIVES.add(DBRef.class); 48 | PRIMITIVES.add(CodeWScope.class); 49 | PRIMITIVES.add(Binary.class); 50 | } 51 | 52 | public static boolean contains(Class clazz) { 53 | if (PRIMITIVES.contains(clazz) || isAJavaPrimitiveArray(clazz)) 54 | return true; 55 | 56 | for (Class primitive : PRIMITIVES) { 57 | if (primitive.isAssignableFrom(clazz)) { 58 | return true; 59 | } 60 | } 61 | return false; 62 | } 63 | 64 | private static boolean isAJavaPrimitiveArray(Class clazz) { 65 | return clazz.isArray() && clazz.getComponentType().isPrimitive(); 66 | } 67 | 68 | private Primitives() { 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/Marshaller.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall; 18 | 19 | import org.jongo.bson.BsonDocument; 20 | 21 | public interface Marshaller { 22 | 23 | BsonDocument marshall(Object pojo) throws MarshallingException; 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/MarshallingException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall; 18 | 19 | public class MarshallingException extends RuntimeException { 20 | 21 | public MarshallingException(String message) { 22 | super(message); 23 | } 24 | 25 | public MarshallingException(String message, Throwable cause) { 26 | super(message, cause); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/Unmarshaller.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall; 18 | 19 | import org.jongo.bson.BsonDocument; 20 | 21 | public interface Unmarshaller { 22 | 23 | T unmarshall(BsonDocument document, Class clazz) throws MarshallingException; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/IdSelector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | public interface IdSelector { 20 | boolean isId(T a); 21 | boolean isObjectId(T a); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/JacksonEngine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import org.jongo.bson.Bson; 21 | import org.jongo.bson.BsonDocument; 22 | import org.jongo.marshall.Marshaller; 23 | import org.jongo.marshall.MarshallingException; 24 | import org.jongo.marshall.Unmarshaller; 25 | import org.jongo.marshall.jackson.configuration.Mapping; 26 | 27 | import java.io.ByteArrayOutputStream; 28 | import java.io.IOException; 29 | 30 | 31 | public class JacksonEngine implements Unmarshaller, Marshaller { 32 | 33 | private final Mapping mapping; 34 | 35 | public JacksonEngine(Mapping mapping) { 36 | this.mapping = mapping; 37 | } 38 | 39 | /** 40 | * @deprecated Use {@link Mapping#getObjectMapper()} instead 41 | */ 42 | @Deprecated 43 | public ObjectMapper getObjectMapper() { 44 | return mapping.getObjectMapper(); 45 | } 46 | 47 | @SuppressWarnings("unchecked") 48 | public T unmarshall(BsonDocument document, Class clazz) throws MarshallingException { 49 | 50 | try { 51 | return (T) mapping.getReader(clazz).readValue(document.toByteArray(), 0, document.getSize()); 52 | } catch (IOException e) { 53 | String message = String.format("Unable to unmarshall result to %s from content %s", clazz, document.toString()); 54 | throw new MarshallingException(message, e); 55 | } 56 | } 57 | 58 | public BsonDocument marshall(Object pojo) throws MarshallingException { 59 | 60 | ByteArrayOutputStream output = new ByteArrayOutputStream(); 61 | try { 62 | mapping.getWriter(pojo).writeValue(output, pojo); 63 | } catch (IOException e) { 64 | throw new MarshallingException("Unable to marshall " + pojo + " into bson", e); 65 | } 66 | return Bson.createDocument(output.toByteArray()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/JacksonIdFieldSelector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | import com.fasterxml.jackson.annotation.JsonProperty; 20 | import org.bson.types.ObjectId; 21 | import org.jongo.ReflectiveObjectIdUpdater; 22 | import org.jongo.marshall.jackson.oid.Id; 23 | import org.jongo.marshall.jackson.oid.MongoId; 24 | import org.jongo.marshall.jackson.oid.MongoObjectId; 25 | 26 | import java.lang.reflect.Field; 27 | 28 | /** 29 | * Use {@link JacksonObjectIdUpdater} instead 30 | */ 31 | @Deprecated 32 | public class JacksonIdFieldSelector implements ReflectiveObjectIdUpdater.IdFieldSelector { 33 | 34 | public boolean isId(Field f) { 35 | return has_IdName(f) || hasJsonProperty(f) || hasIdAnnotation(f); 36 | } 37 | 38 | public boolean isObjectId(Field f) { 39 | return f.isAnnotationPresent(org.jongo.marshall.jackson.oid.ObjectId.class) 40 | || f.isAnnotationPresent(MongoObjectId.class) 41 | || ObjectId.class.isAssignableFrom(f.getType()); 42 | } 43 | 44 | private boolean has_IdName(Field f) { 45 | return "_id".equals(f.getName()); 46 | } 47 | 48 | private boolean hasJsonProperty(Field f) { 49 | JsonProperty annotation = f.getAnnotation(JsonProperty.class); 50 | return annotation != null && "_id".equals(annotation.value()); 51 | } 52 | 53 | private boolean hasIdAnnotation(Field f) { 54 | Id id = f.getAnnotation(Id.class); 55 | MongoId mongoId = f.getAnnotation(MongoId.class); 56 | return id != null || mongoId != null; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/JacksonMapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import org.jongo.Mapper; 21 | import org.jongo.ObjectIdUpdater; 22 | import org.jongo.marshall.Marshaller; 23 | import org.jongo.marshall.Unmarshaller; 24 | import org.jongo.marshall.jackson.configuration.AbstractMappingBuilder; 25 | import org.jongo.marshall.jackson.configuration.Mapping; 26 | import org.jongo.query.BsonQueryFactory; 27 | import org.jongo.query.QueryFactory; 28 | 29 | public class JacksonMapper implements Mapper { 30 | 31 | private final JacksonEngine engine; 32 | private final ObjectIdUpdater objectIdUpdater; 33 | private final QueryFactory queryFactory; 34 | 35 | private JacksonMapper(JacksonEngine engine, QueryFactory queryFactory, ObjectIdUpdater objectIdUpdater) { 36 | this.engine = engine; 37 | this.queryFactory = queryFactory; 38 | this.objectIdUpdater = objectIdUpdater; 39 | } 40 | 41 | public Marshaller getMarshaller() { 42 | return engine; 43 | } 44 | 45 | public Unmarshaller getUnmarshaller() { 46 | return engine; 47 | } 48 | 49 | public ObjectIdUpdater getObjectIdUpdater() { 50 | return objectIdUpdater; 51 | } 52 | 53 | public QueryFactory getQueryFactory() { 54 | return queryFactory; 55 | } 56 | 57 | public static class Builder extends AbstractMappingBuilder { 58 | 59 | private QueryFactory queryFactory; 60 | private ObjectIdUpdater objectIdUpdater; 61 | 62 | public Builder() { 63 | super(); 64 | } 65 | 66 | public Builder(ObjectMapper mapper) { 67 | super(mapper); 68 | } 69 | 70 | public Mapper build() { 71 | Mapping mapping = createMapping(); 72 | JacksonEngine jacksonEngine = new JacksonEngine(mapping); 73 | if (queryFactory == null) { 74 | queryFactory = new BsonQueryFactory(jacksonEngine); 75 | } 76 | if (objectIdUpdater == null) { 77 | objectIdUpdater = new JacksonObjectIdUpdater(mapping.getObjectMapper()); 78 | } 79 | return new JacksonMapper(jacksonEngine, queryFactory, objectIdUpdater); 80 | } 81 | 82 | public Builder withQueryFactory(QueryFactory factory) { 83 | this.queryFactory = factory; 84 | return getBuilderInstance(); 85 | } 86 | 87 | public Builder withObjectIdUpdater(ObjectIdUpdater objectIdUpdater) { 88 | this.objectIdUpdater = objectIdUpdater; 89 | return getBuilderInstance(); 90 | } 91 | 92 | @Override 93 | protected Builder getBuilderInstance() { 94 | return this; 95 | } 96 | 97 | public static Builder jacksonMapper() { 98 | return new Builder(); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/JongoAnnotationIntrospector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | import com.fasterxml.jackson.annotation.JsonInclude.Include; 20 | import com.fasterxml.jackson.databind.PropertyName; 21 | import com.fasterxml.jackson.databind.introspect.Annotated; 22 | import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector; 23 | import org.jongo.marshall.jackson.oid.*; 24 | 25 | @SuppressWarnings("deprecation") 26 | public class JongoAnnotationIntrospector extends NopAnnotationIntrospector { 27 | 28 | private final IdSelector idSelector; 29 | 30 | public JongoAnnotationIntrospector() { 31 | this(new AnnotatedIdSelector()); 32 | } 33 | 34 | public JongoAnnotationIntrospector(IdSelector idSelector) { 35 | this.idSelector = idSelector; 36 | } 37 | 38 | @Override 39 | public Include findSerializationInclusion(Annotated a, Include defValue) { 40 | return idSelector.isObjectId(a) ? Include.NON_NULL : defValue; 41 | } 42 | 43 | @Override 44 | public Object findSerializer(Annotated a) { 45 | return idSelector.isObjectId(a) ? ObjectIdSerializer.class : super.findSerializer(a); 46 | } 47 | 48 | @Override 49 | public Object findDeserializer(Annotated a) { 50 | return idSelector.isObjectId(a) ? ObjectIdDeserializer.class : super.findDeserializer(a); 51 | } 52 | 53 | @Override 54 | public PropertyName findNameForSerialization(Annotated a) { 55 | return idSelector.isId(a) ? new PropertyName("_id") : super.findNameForSerialization(a); 56 | } 57 | 58 | @Override 59 | public PropertyName findNameForDeserialization(Annotated a) { 60 | return idSelector.isId(a) ? new PropertyName("_id") : super.findNameForDeserialization(a); 61 | } 62 | 63 | public static class AnnotatedIdSelector implements IdSelector { 64 | 65 | public boolean isId(Annotated a) { 66 | return a.hasAnnotation(MongoId.class) || a.hasAnnotation(Id.class); 67 | } 68 | 69 | public boolean isObjectId(Annotated a) { 70 | return a.hasAnnotation(MongoObjectId.class) || a.hasAnnotation(ObjectId.class); 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/bson4jackson/BsonModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.bson4jackson; 18 | 19 | public class BsonModule extends de.undercouch.bson4jackson.BsonModule { 20 | 21 | @Override 22 | public void setupModule(SetupContext context) { 23 | super.setupModule(context); 24 | context.addSerializers(new BsonSerializers()); 25 | context.addDeserializers(new BsonDeserializers()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/bson4jackson/MongoBsonFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.bson4jackson; 18 | 19 | import com.fasterxml.jackson.core.JsonEncoding; 20 | import com.fasterxml.jackson.core.ObjectCodec; 21 | import com.fasterxml.jackson.core.io.IOContext; 22 | import de.undercouch.bson4jackson.BsonFactory; 23 | import de.undercouch.bson4jackson.BsonGenerator; 24 | import de.undercouch.bson4jackson.BsonParser; 25 | 26 | import java.io.IOException; 27 | import java.io.InputStream; 28 | import java.io.OutputStream; 29 | 30 | public class MongoBsonFactory extends BsonFactory { 31 | 32 | public static BsonFactory createFactory() { 33 | BsonFactory factory = new MongoBsonFactory(); 34 | factory.enable(BsonParser.Feature.HONOR_DOCUMENT_LENGTH); 35 | return factory; 36 | } 37 | 38 | @Override 39 | protected BsonParser _createParser(InputStream in, IOContext ctxt) { 40 | BsonParser p = new MongoBsonParser(ctxt, _parserFeatures, _bsonParserFeatures, in); 41 | ObjectCodec codec = getCodec(); 42 | if (codec != null) { 43 | p.setCodec(codec); 44 | } 45 | return p; 46 | } 47 | 48 | @Override 49 | public BsonGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException { 50 | 51 | IOContext ctxt = _createContext(out, true); 52 | ctxt.setEncoding(enc); 53 | if (enc == JsonEncoding.UTF8 && _outputDecorator != null) { 54 | out = _outputDecorator.decorate(ctxt, out); 55 | } 56 | BsonGenerator g = new MongoBsonGenerator(_generatorFeatures, _bsonGeneratorFeatures, out); 57 | ObjectCodec codec = getCodec(); 58 | if (codec != null) { 59 | g.setCodec(codec); 60 | } 61 | if (_characterEscapes != null) { 62 | g.setCharacterEscapes(_characterEscapes); 63 | } 64 | return g; 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/bson4jackson/MongoBsonGenerator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.bson4jackson; 18 | 19 | import de.undercouch.bson4jackson.BsonConstants; 20 | import de.undercouch.bson4jackson.BsonGenerator; 21 | import org.bson.types.*; 22 | 23 | import java.io.IOException; 24 | import java.io.OutputStream; 25 | 26 | class MongoBsonGenerator extends BsonGenerator { 27 | 28 | public MongoBsonGenerator(int jsonFeatures, int bsonFeatures, OutputStream out) { 29 | super(jsonFeatures, bsonFeatures, out); 30 | } 31 | 32 | public void writeNativeObjectId(org.bson.types.ObjectId objectId) throws IOException { 33 | _writeArrayFieldNameIfNeeded(); 34 | _verifyValueWrite("write datetime"); 35 | _buffer.putByte(_typeMarker, BsonConstants.TYPE_OBJECTID); 36 | _buffer.putBytes(objectId.toByteArray()); 37 | flushBuffer(); 38 | } 39 | 40 | public void writeBSONTimestamp(BSONTimestamp timestamp) throws IOException { 41 | _writeArrayFieldNameIfNeeded(); 42 | _verifyValueWrite("write timestamp"); 43 | _buffer.putByte(_typeMarker, BsonConstants.TYPE_TIMESTAMP); 44 | _buffer.putInt(timestamp.getInc()); 45 | _buffer.putInt(timestamp.getTime()); 46 | flushBuffer(); 47 | } 48 | 49 | public void writeMinKey(MinKey key) throws IOException { 50 | _writeArrayFieldNameIfNeeded(); 51 | _verifyValueWrite("write int"); 52 | _buffer.putByte(_typeMarker, BsonConstants.TYPE_MINKEY); 53 | flushBuffer(); 54 | } 55 | 56 | public void writeMaxKey(MaxKey key) throws IOException { 57 | _writeArrayFieldNameIfNeeded(); 58 | _verifyValueWrite("write boolean"); 59 | _buffer.putByte(_typeMarker, BsonConstants.TYPE_MAXKEY); 60 | flushBuffer(); 61 | } 62 | 63 | public void writeBinary(Binary binary) throws IOException { 64 | _writeArrayFieldNameIfNeeded(); 65 | _verifyValueWrite("write binary"); 66 | byte[] bytes = binary.getData(); 67 | _buffer.putByte(_typeMarker, BsonConstants.TYPE_BINARY); 68 | _buffer.putInt(bytes.length); 69 | _buffer.putByte(binary.getType()); 70 | _buffer.putBytes(binary.getData()); 71 | flushBuffer(); 72 | } 73 | 74 | public void writeDecima128(Decimal128 decimal) throws IOException { 75 | _writeArrayFieldNameIfNeeded(); 76 | _verifyValueWrite("write number"); 77 | _buffer.putByte(_typeMarker, BsonConstants.TYPE_DECIMAL128); 78 | _buffer.putLong(decimal.getLow()); 79 | _buffer.putLong(decimal.getHigh()); 80 | flushBuffer(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/AnnotationModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.AnnotationIntrospector; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair; 22 | import org.jongo.marshall.jackson.JongoAnnotationIntrospector; 23 | 24 | public class AnnotationModifier implements MapperModifier { 25 | 26 | public void modify(ObjectMapper mapper) { 27 | AnnotationIntrospector jongoIntrospector = new JongoAnnotationIntrospector(); 28 | AnnotationIntrospector defaultIntrospector = mapper.getSerializationConfig().getAnnotationIntrospector(); 29 | AnnotationIntrospector pair = new AnnotationIntrospectorPair(jongoIntrospector, defaultIntrospector); 30 | 31 | mapper.setAnnotationIntrospector(pair); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/DefaultReaderCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectReader; 21 | 22 | class DefaultReaderCallback implements ReaderCallback { 23 | public ObjectReader getReader(ObjectMapper mapper, Class clazz) { 24 | return mapper.reader(clazz); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/DefaultWriterCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectWriter; 21 | 22 | class DefaultWriterCallback implements WriterCallback { 23 | public ObjectWriter getWriter(ObjectMapper mapper, Object pojo) { 24 | return mapper.writer(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/DeserializationFeatureModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.DeserializationFeature; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | 22 | class DeserializationFeatureModifier implements MapperModifier { 23 | private final DeserializationFeature feature; 24 | private final boolean enable; 25 | 26 | public DeserializationFeatureModifier(DeserializationFeature feature, boolean enable) { 27 | this.feature = feature; 28 | this.enable = enable; 29 | } 30 | 31 | public void modify(ObjectMapper mapper) { 32 | if (enable) 33 | mapper.enable(feature); 34 | else 35 | mapper.disable(feature); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/MapperFeatureModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.MapperFeature; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | 22 | class MapperFeatureModifier implements MapperModifier { 23 | private final MapperFeature feature; 24 | private final boolean enable; 25 | 26 | public MapperFeatureModifier(MapperFeature feature, boolean enable) { 27 | this.feature = feature; 28 | this.enable = enable; 29 | } 30 | 31 | public void modify(ObjectMapper mapper) { 32 | if (enable) 33 | mapper.enable(feature); 34 | else 35 | mapper.disable(feature); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/MapperModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | 21 | public interface MapperModifier { 22 | 23 | void modify(ObjectMapper mapper); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/Mapping.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectReader; 21 | import com.fasterxml.jackson.databind.ObjectWriter; 22 | 23 | public class Mapping { 24 | 25 | private ObjectMapper mapper; 26 | private ReaderCallback readerCallback; 27 | private WriterCallback writerCallback; 28 | 29 | public Mapping(ObjectMapper mapper, ReaderCallback readerCallback, WriterCallback writerCallback) { 30 | this.mapper = mapper; 31 | this.readerCallback = readerCallback; 32 | this.writerCallback = writerCallback; 33 | } 34 | 35 | public ObjectReader getReader(Class clazz) { 36 | return readerCallback.getReader(mapper, clazz); 37 | } 38 | 39 | public ObjectWriter getWriter(Object pojo) { 40 | return writerCallback.getWriter(mapper, pojo); 41 | } 42 | 43 | public ObjectMapper getObjectMapper() { 44 | return mapper; 45 | } 46 | 47 | public static Mapping defaultMapping() { 48 | return new Builder().build(); 49 | } 50 | 51 | public static class Builder extends AbstractMappingBuilder { 52 | 53 | public Builder() { 54 | super(); 55 | } 56 | 57 | public Builder(ObjectMapper mapper) { 58 | super(mapper); 59 | } 60 | 61 | @Override 62 | protected Builder getBuilderInstance() { 63 | return this; 64 | } 65 | 66 | public Mapping build() { 67 | return createMapping(); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/PropertyModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | 21 | import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; 22 | import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; 23 | 24 | public class PropertyModifier implements MapperModifier { 25 | 26 | public void modify(ObjectMapper mapper) { 27 | mapper.disable(FAIL_ON_UNKNOWN_PROPERTIES); 28 | mapper.setSerializationInclusion(NON_NULL); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/ReaderCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectReader; 21 | 22 | public interface ReaderCallback { 23 | 24 | ObjectReader getReader(ObjectMapper mapper, Class clazz); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/SerializationFeatureModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.SerializationFeature; 21 | 22 | class SerializationFeatureModifier implements MapperModifier { 23 | private final SerializationFeature feature; 24 | private final boolean enable; 25 | 26 | public SerializationFeatureModifier(SerializationFeature feature, boolean enable) { 27 | this.feature = feature; 28 | this.enable = enable; 29 | } 30 | 31 | public void modify(ObjectMapper mapper) { 32 | if (enable) 33 | mapper.enable(feature); 34 | else 35 | mapper.disable(feature); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/ViewReaderCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectReader; 21 | 22 | class ViewReaderCallback implements ReaderCallback { 23 | private final Class viewClass; 24 | 25 | public ViewReaderCallback(Class viewClass) { 26 | this.viewClass = viewClass; 27 | } 28 | 29 | public ObjectReader getReader(ObjectMapper mapper, Class clazz) { 30 | return mapper.reader(clazz).withView(viewClass); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/ViewWriterCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectWriter; 21 | 22 | class ViewWriterCallback implements WriterCallback { 23 | private final Class viewClass; 24 | 25 | public ViewWriterCallback(Class viewClass) { 26 | this.viewClass = viewClass; 27 | } 28 | 29 | public ObjectWriter getWriter(ObjectMapper mapper, Object pojo) { 30 | return mapper.writerWithView(viewClass); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/VisibilityModifier.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.introspect.VisibilityChecker; 21 | 22 | import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY; 23 | import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_GETTERS; 24 | import static com.fasterxml.jackson.databind.MapperFeature.AUTO_DETECT_SETTERS; 25 | 26 | public class VisibilityModifier implements MapperModifier { 27 | 28 | public void modify(ObjectMapper mapper) { 29 | mapper.disable(AUTO_DETECT_SETTERS); 30 | mapper.disable(AUTO_DETECT_GETTERS); 31 | 32 | VisibilityChecker checker = mapper.getSerializationConfig().getDefaultVisibilityChecker(); 33 | mapper.setVisibilityChecker(checker.withFieldVisibility(ANY)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/configuration/WriterCallback.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.fasterxml.jackson.databind.ObjectWriter; 21 | 22 | public interface WriterCallback { 23 | 24 | ObjectWriter getWriter(ObjectMapper mapper, Object pojo); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/oid/Id.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; 20 | import com.fasterxml.jackson.annotation.JsonProperty; 21 | 22 | import java.lang.annotation.Retention; 23 | 24 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 25 | 26 | @Deprecated 27 | @Retention(RUNTIME) 28 | @JacksonAnnotationsInside 29 | 30 | @JsonProperty("_id") 31 | /** 32 | * This class has been deprecated because it has side effects when used with an external Jackson ObjectMapper. 33 | * It will be removed in a future release. 34 | * Use @MongoId instead. 35 | */ 36 | public @interface Id { 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/oid/MongoId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import java.lang.annotation.Retention; 20 | 21 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 22 | 23 | @Retention(RUNTIME) 24 | public @interface MongoId { 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/oid/MongoObjectId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import java.lang.annotation.Retention; 20 | 21 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 22 | 23 | @Retention(RUNTIME) 24 | public @interface MongoObjectId { 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/oid/ObjectId.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; 20 | import com.fasterxml.jackson.annotation.JsonInclude; 21 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 22 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 23 | 24 | import java.lang.annotation.Retention; 25 | 26 | import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; 27 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 28 | 29 | @Deprecated 30 | @Retention(RUNTIME) 31 | @JacksonAnnotationsInside 32 | 33 | @JsonInclude(NON_NULL) 34 | @JsonSerialize(using = ObjectIdSerializer.class) 35 | @JsonDeserialize(using = ObjectIdDeserializer.class) 36 | /** 37 | * This class has been deprecated because it has side effects when used with an external Jackson ObjectMapper. 38 | * It will be removed in a future release. 39 | * Use @MongoObjectId instead. 40 | */ 41 | public @interface ObjectId { 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/oid/ObjectIdDeserializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import com.fasterxml.jackson.core.JsonParser; 20 | import com.fasterxml.jackson.core.TreeNode; 21 | import com.fasterxml.jackson.databind.*; 22 | import com.fasterxml.jackson.databind.deser.ContextualDeserializer; 23 | import org.bson.types.ObjectId; 24 | 25 | import java.io.IOException; 26 | 27 | import static org.jongo.MongoCollection.MONGO_QUERY_OID; 28 | 29 | public class ObjectIdDeserializer extends JsonDeserializer implements ContextualDeserializer { 30 | 31 | private boolean fieldIsObjectId = false; 32 | 33 | public ObjectIdDeserializer() { 34 | this(false); 35 | } 36 | 37 | public ObjectIdDeserializer(boolean fieldIsObjectId) { 38 | this.fieldIsObjectId = fieldIsObjectId; 39 | } 40 | 41 | @Override 42 | public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { 43 | TreeNode treeNode = jp.readValueAsTree(); 44 | JsonNode oid = ((JsonNode) treeNode).get(MONGO_QUERY_OID); 45 | if (fieldIsObjectId) { 46 | if (oid != null) { 47 | return new ObjectId(oid.asText()); 48 | } else { 49 | return new ObjectId(((JsonNode) treeNode).asText()); 50 | } 51 | } else { 52 | if (oid != null) { 53 | return oid.asText(); 54 | } else { 55 | return ((JsonNode) treeNode).asText(); 56 | } 57 | } 58 | } 59 | 60 | public JsonDeserializer createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException { 61 | return new ObjectIdDeserializer(ObjectId.class.isAssignableFrom(property.getType().getRawClass())); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/marshall/jackson/oid/ObjectIdSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import com.fasterxml.jackson.core.JsonGenerator; 20 | import com.fasterxml.jackson.databind.BeanProperty; 21 | import com.fasterxml.jackson.databind.JsonMappingException; 22 | import com.fasterxml.jackson.databind.JsonSerializer; 23 | import com.fasterxml.jackson.databind.SerializerProvider; 24 | import com.fasterxml.jackson.databind.ser.ContextualSerializer; 25 | import org.bson.types.ObjectId; 26 | 27 | import java.io.IOException; 28 | 29 | public class ObjectIdSerializer extends JsonSerializer 30 | implements ContextualSerializer { 31 | 32 | boolean fieldIsObjectId = false; 33 | 34 | public ObjectIdSerializer() { 35 | this(false); 36 | } 37 | 38 | public ObjectIdSerializer(boolean serializeAsObjectId) { 39 | this.fieldIsObjectId = serializeAsObjectId; 40 | } 41 | 42 | @Override 43 | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { 44 | if (value == null) { 45 | jgen.writeNull(); 46 | } else if (fieldIsObjectId) { 47 | jgen.writeObject(value); 48 | } else { 49 | jgen.writeObject(new ObjectId(value.toString())); 50 | } 51 | } 52 | 53 | public JsonSerializer createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException { 54 | return new ObjectIdSerializer(ObjectId.class.isAssignableFrom(property.getType().getRawClass())); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/query/Context.java: -------------------------------------------------------------------------------- 1 | package org.jongo.query; 2 | 3 | enum Context { 4 | NONE, 5 | OBJECT, 6 | ARRAY, 7 | STRING; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/query/Query.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.query; 18 | 19 | import com.mongodb.DBObject; 20 | import org.bson.BsonDocument; 21 | 22 | public interface Query { 23 | 24 | DBObject toDBObject(); 25 | 26 | BsonDocument toBsonDocument(); 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/query/QueryFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.query; 18 | 19 | public interface QueryFactory { 20 | Query createQuery(String query, Object... parameters); 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/jongo/query/Stack.java: -------------------------------------------------------------------------------- 1 | package org.jongo.query; 2 | 3 | import java.util.LinkedList; 4 | 5 | class Stack { 6 | private final LinkedList stack; 7 | private final T noValue; 8 | 9 | Stack(T noValue) { 10 | this.stack = new LinkedList<>(); 11 | this.noValue = noValue; 12 | } 13 | 14 | public T peek() { 15 | if (stack.isEmpty()) { 16 | return noValue; 17 | } 18 | 19 | return stack.peekLast(); 20 | } 21 | 22 | public T pop() { 23 | if (stack.isEmpty()) { 24 | return noValue; 25 | } 26 | 27 | return this.stack.removeLast(); 28 | } 29 | 30 | public void push(T value) { 31 | this.stack.addLast(value); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/AlreadyCheckDBObjectTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCollection; 20 | import com.mongodb.DBObject; 21 | import com.mongodb.WriteConcern; 22 | import org.bson.types.ObjectId; 23 | import org.jongo.model.Friend; 24 | import org.jongo.util.JongoTestBase; 25 | import org.junit.Test; 26 | import org.mockito.ArgumentCaptor; 27 | 28 | import static org.assertj.core.api.Assertions.assertThat; 29 | import static org.mockito.Matchers.eq; 30 | import static org.mockito.Mockito.*; 31 | 32 | public class AlreadyCheckDBObjectTest extends JongoTestBase { 33 | 34 | ArgumentCaptor captor = ArgumentCaptor.forClass(DBObject.class); 35 | DBCollection mockedDBCollection = mock(DBCollection.class); 36 | ObjectIdUpdater objectIdUpdater = mock(ObjectIdUpdater.class); 37 | 38 | @Test 39 | public void shouldPreventLazyDBObjectToBeDeserialized() throws Exception { 40 | 41 | Friend friend = new Friend(ObjectId.get(), "John"); 42 | ObjectId deserializedOid = ObjectId.get(); 43 | when(objectIdUpdater.getId(friend)).thenReturn(deserializedOid); 44 | Insert insert = new Insert(mockedDBCollection, WriteConcern.UNACKNOWLEDGED, getMapper().getMarshaller(), objectIdUpdater, getMapper().getQueryFactory()); 45 | 46 | insert.save(friend); 47 | 48 | verify(mockedDBCollection).save(captor.capture(), eq(WriteConcern.UNACKNOWLEDGED)); 49 | DBObject value = captor.getValue(); 50 | assertThat(value.get("_id")).isEqualTo(deserializedOid); 51 | } 52 | 53 | @Test 54 | public void shouldNotPreventLazyDBObjectToBeDeserializedWhenOidIsNull() throws Exception { 55 | 56 | ObjectId id = ObjectId.get(); 57 | Friend friend = new Friend(id, "John"); 58 | when(objectIdUpdater.getId(friend)).thenReturn(null); 59 | Insert insert = new Insert(mockedDBCollection, WriteConcern.UNACKNOWLEDGED, getMapper().getMarshaller(), objectIdUpdater, getMapper().getQueryFactory()); 60 | 61 | insert.save(friend); 62 | 63 | verify(mockedDBCollection).save(captor.capture(), eq(WriteConcern.UNACKNOWLEDGED)); 64 | DBObject value = captor.getValue(); 65 | assertThat(value.get("_id")).isNotNull(); 66 | assertThat(value.get("_id")).isEqualTo(id); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/AnnotationsMisusedTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | 20 | import com.mongodb.WriteConcern; 21 | import junit.framework.Assert; 22 | import org.bson.types.ObjectId; 23 | import org.jongo.marshall.jackson.oid.Id; 24 | import org.jongo.marshall.jackson.oid.MongoId; 25 | import org.jongo.model.ExternalFriend; 26 | import org.jongo.util.JongoTestBase; 27 | import org.junit.After; 28 | import org.junit.Before; 29 | import org.junit.Test; 30 | 31 | import static org.assertj.core.api.Assertions.assertThat; 32 | 33 | public class AnnotationsMisusedTest extends JongoTestBase { 34 | 35 | private MongoCollection collection; 36 | 37 | @Before 38 | public void setUp() throws Exception { 39 | collection = createEmptyCollection("friends"); 40 | } 41 | 42 | @After 43 | public void tearDown() throws Exception { 44 | dropCollection("friends"); 45 | } 46 | 47 | @Test 48 | public void savingAPojoWithAnEmptyStringCustomId() throws Exception { 49 | 50 | ExternalFriend friend = ExternalFriend.createFriendWithoutId("Robert"); 51 | 52 | collection.withWriteConcern(WriteConcern.MAJORITY).save(friend); 53 | 54 | ExternalFriend externalFriend = collection.findOne().as(ExternalFriend.class); 55 | 56 | /* 57 | * Works because Bson4jackson try to convert ObjectId into String 58 | * see com.fasterxml.jackson.databind.deser.std.StringDeserializer 59 | */ 60 | assertThat(ObjectId.isValid(externalFriend.getId())).isTrue(); 61 | } 62 | 63 | @Test 64 | public void savingAPojoWithAnEmptyCustomIntegerId() throws Exception { 65 | 66 | WithIntegerId custom = new WithIntegerId(); 67 | 68 | collection.withWriteConcern(WriteConcern.MAJORITY).save(custom); 69 | 70 | try { 71 | collection.findOne().as(WithIntegerId.class); 72 | Assert.fail("Should not be able to unmarshall an ObjectId into an Integer"); 73 | } catch (Exception e) { 74 | } 75 | } 76 | 77 | private static class WithIntegerId { 78 | @Id//see DeprecatedAnnotationsCompatibilitySuiteTest for more informations 79 | @MongoId 80 | private Integer id; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/CountTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.ReadConcern; 20 | import com.mongodb.ReadPreference; 21 | import org.jongo.model.Friend; 22 | import org.jongo.util.JongoTestBase; 23 | import org.junit.After; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | 29 | public class CountTest extends JongoTestBase { 30 | 31 | private MongoCollection collection; 32 | 33 | @Before 34 | public void setUp() throws Exception { 35 | collection = createEmptyCollection("friends"); 36 | } 37 | 38 | @After 39 | public void tearDown() throws Exception { 40 | dropCollection("friends"); 41 | } 42 | 43 | public Friend newFriend() { 44 | return new Friend("John", "22 Wall Street Avenue"); 45 | } 46 | 47 | @Test 48 | public void canCount() throws Exception { 49 | /* given */ 50 | collection.save(newFriend()); 51 | collection.save(newFriend()); 52 | 53 | /* then */ 54 | assertThat(collection.count()).isEqualTo(2); 55 | } 56 | 57 | @Test 58 | public void canCountWithQuery() throws Exception { 59 | /* given */ 60 | collection.save(newFriend()); 61 | collection.save(newFriend()); 62 | 63 | /* then */ 64 | assertThat(collection.count("{name:{$exists:true}}")).isEqualTo(2); 65 | } 66 | 67 | @Test 68 | public void canCountWithParameters() throws Exception { 69 | /* given */ 70 | collection.save(newFriend()); 71 | collection.save(new Friend("Peter", "22 Wall Street Avenue")); 72 | 73 | /* then */ 74 | assertThat(collection.count("{name:#}", "Peter")).isEqualTo(1); 75 | } 76 | 77 | @Test 78 | public void canCountWithReadPreference() throws Exception { 79 | /* given */ 80 | collection.save(newFriend()); 81 | collection.save(newFriend()); 82 | 83 | /* then */ 84 | assertThat(collection.withReadPreference(ReadPreference.primaryPreferred()).count()).isEqualTo(2); 85 | 86 | // warning: we cannot check that ReadPreference is really used by driver, this unit test only checks the API 87 | } 88 | 89 | @Test 90 | public void canCountWithReadConcern() throws Exception { 91 | /* given */ 92 | collection.save(newFriend()); 93 | collection.save(newFriend()); 94 | 95 | /* then */ 96 | assertThat(collection.withReadConcern(ReadConcern.DEFAULT).count()).isEqualTo(2); 97 | 98 | // warning: we cannot check that ReadConcern is really used by driver, this unit test only checks the API 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/FindSkipSortLimitTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import org.jongo.model.Friend; 20 | import org.jongo.util.JongoTestBase; 21 | import org.junit.After; 22 | import org.junit.Before; 23 | import org.junit.Test; 24 | 25 | import java.util.Iterator; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | 29 | public class FindSkipSortLimitTest extends JongoTestBase { 30 | 31 | private MongoCollection collection; 32 | 33 | @Before 34 | public void setUp() throws Exception { 35 | collection = createEmptyCollection("friends"); 36 | } 37 | 38 | @After 39 | public void tearDown() throws Exception { 40 | dropCollection("friends"); 41 | } 42 | 43 | public Friend newFriend() { 44 | return new Friend("John", "22 Wall Street Avenue"); 45 | } 46 | 47 | @Test 48 | public void canLimit() throws Exception { 49 | /* given */ 50 | collection.save(newFriend()); 51 | collection.save(newFriend()); 52 | collection.save(newFriend()); 53 | 54 | /* when */ 55 | Iterable results = collection.find().limit(2).as(Friend.class); 56 | 57 | /* then */ 58 | assertThat(results).hasSize(2); 59 | } 60 | 61 | @Test 62 | public void canSkip() throws Exception { 63 | /* given */ 64 | collection.save(newFriend()); 65 | collection.save(newFriend()); 66 | collection.save(newFriend()); 67 | 68 | /* when */ 69 | Iterable results = collection.find().skip(2).as(Friend.class); 70 | 71 | /* then */ 72 | assertThat(results).hasSize(1); 73 | } 74 | 75 | @Test 76 | public void canSort() throws Exception { 77 | /* given */ 78 | collection.save(new Friend("John", "23 Wall Street Av.")); 79 | collection.save(new Friend("John", "21 Wall Street Av.")); 80 | collection.save(new Friend("John", "22 Wall Street Av.")); 81 | 82 | /* when */ 83 | Iterator results = collection.find("{}").sort("{'address':1}").as(Friend.class); 84 | 85 | /* then */ 86 | assertThat(results.next().getAddress()).isEqualTo("21 Wall Street Av."); 87 | assertThat(results.next().getAddress()).isEqualTo("22 Wall Street Av."); 88 | assertThat(results.next().getAddress()).isEqualTo("23 Wall Street Av."); 89 | assertThat(results.hasNext()).isFalse(); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/FindWithModifierTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCursor; 20 | import org.bson.types.ObjectId; 21 | import org.jongo.model.Friend; 22 | import org.jongo.util.JongoTestBase; 23 | import org.junit.After; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | 27 | import java.util.Iterator; 28 | 29 | import static org.assertj.core.api.Assertions.assertThat; 30 | 31 | 32 | public class FindWithModifierTest extends JongoTestBase { 33 | 34 | private MongoCollection collection; 35 | 36 | @Before 37 | public void setUp() throws Exception { 38 | collection = createEmptyCollection("friends"); 39 | } 40 | 41 | @After 42 | public void tearDown() throws Exception { 43 | dropCollection("friends"); 44 | } 45 | 46 | @Test 47 | public void canFindWithHint() throws Exception { 48 | /* given */ 49 | Friend noName = new Friend(new ObjectId(), null); 50 | collection.save(noName); 51 | 52 | collection.ensureIndex("{name: 1}", "{sparse: true}"); 53 | 54 | /* when */ 55 | // force to use _id index instead of name index which is sparsed 56 | Iterator friends = collection.find().hint("{$natural: 1}").sort("{name: 1}").as(Friend.class); 57 | 58 | /* then */ 59 | assertThat(friends.hasNext()).isTrue(); 60 | } 61 | 62 | @Test 63 | public void canUseQueryModifier() throws Exception { 64 | /* given */ 65 | collection.save(new Friend(new ObjectId(), "John")); 66 | collection.save(new Friend(new ObjectId(), "Robert")); 67 | 68 | /* when */ 69 | Iterator friends = collection.find() 70 | .with(new QueryModifier() { 71 | public void modify(DBCursor cursor) { 72 | cursor.limit(1); 73 | } 74 | }) 75 | .as(Friend.class); 76 | 77 | /* then */ 78 | assertThat(friends.hasNext()).isTrue(); 79 | friends.next(); 80 | assertThat(friends.hasNext()).isFalse(); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/FindWithResultMapperTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBObject; 20 | import org.jongo.model.Friend; 21 | import org.jongo.util.JongoTestBase; 22 | import org.junit.After; 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | 26 | import static org.assertj.core.api.Assertions.assertThat; 27 | 28 | public class FindWithResultMapperTest extends JongoTestBase { 29 | 30 | private MongoCollection collection; 31 | 32 | @Before 33 | public void setUp() throws Exception { 34 | collection = createEmptyCollection("friends"); 35 | } 36 | 37 | @After 38 | public void tearDown() throws Exception { 39 | dropCollection("friends"); 40 | } 41 | 42 | @Test 43 | public void canFindAndMap() throws Exception { 44 | /* given */ 45 | ResultHandler handler = new RawResultHandler(); 46 | collection.save(new Friend("John", "22 Wall Street Avenue")); 47 | collection.save(new Friend("Peter", "22 Wall Street Avenue")); 48 | 49 | /* when */ 50 | for (DBObject result : collection.find().map(handler)) { 51 | /* then */ 52 | assertThat(result.get("name")).isIn("John", "Peter"); 53 | } 54 | } 55 | 56 | @Test 57 | public void canFindOneAndMap() throws Exception { 58 | /* given */ 59 | ResultHandler handler = new RawResultHandler(); 60 | Friend john = new Friend("John", "22 Wall Street Avenue"); 61 | collection.save(john); 62 | 63 | /* when */ 64 | DBObject result = collection.findOne().map(handler); 65 | 66 | /* then */ 67 | assertThat(result.get("name")).isEqualTo("John"); 68 | 69 | 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/GridFsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.BasicDBObject; 20 | import com.mongodb.gridfs.GridFS; 21 | import com.mongodb.gridfs.GridFSDBFile; 22 | import com.mongodb.gridfs.GridFSInputFile; 23 | import org.jongo.util.JongoTestBase; 24 | import org.junit.After; 25 | import org.junit.Before; 26 | import org.junit.Test; 27 | 28 | import static org.assertj.core.api.Assertions.assertThat; 29 | import static org.jongo.RawResultHandler.asRaw; 30 | 31 | public class GridFsTest extends JongoTestBase { 32 | 33 | GridFS gridFS; 34 | 35 | @Before 36 | public void setUp() throws Exception { 37 | gridFS = new GridFS(getDatabase()); 38 | insertTestFileInGridFS(); 39 | } 40 | 41 | @Test 42 | public void shouldAllowDualAccessToFilesCollection() throws Exception { 43 | queryWithJongoAndMapToCustomClass(); 44 | queryWithJongoAndMapToGridFSDBFile(); 45 | queryWithGridFS(); 46 | } 47 | 48 | @After 49 | public void tearDown() throws Exception { 50 | dropGridFsCollections(); 51 | } 52 | 53 | private void insertTestFileInGridFS() { 54 | GridFSInputFile gridFile = gridFS.createFile(new byte[]{ 55 | (byte) 0xCA, 56 | (byte) 0xFE, 57 | (byte) 0xBA, 58 | (byte) 0xBE}); 59 | gridFile.setFilename("test.txt"); 60 | gridFile.save(); 61 | } 62 | 63 | private void queryWithJongoAndMapToCustomClass() { 64 | CustomFileDescriptor descriptor = getJongo().getCollection("fs.files") 65 | .findOne() 66 | .as(CustomFileDescriptor.class); 67 | assertThat(descriptor.filename).isEqualTo("test.txt"); 68 | } 69 | 70 | private void queryWithJongoAndMapToGridFSDBFile() { 71 | GridFSDBFile gridFile = getJongo().getCollection("fs.files") 72 | .findOne() 73 | .map(asRaw(GridFSDBFile.class)); 74 | assertThat(gridFile.getFilename()).isEqualTo("test.txt"); 75 | } 76 | 77 | private void queryWithGridFS() { 78 | GridFSDBFile gridFile = gridFS.findOne(new BasicDBObject()); 79 | assertThat(gridFile.getFilename()).isEqualTo("test.txt"); 80 | } 81 | 82 | private void dropGridFsCollections() throws Exception { 83 | getDatabase().getCollection("fs.files").drop(); 84 | getDatabase().getCollection("fs.chunks").drop(); 85 | } 86 | 87 | static class CustomFileDescriptor { 88 | String filename; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/JongoTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import org.jongo.model.Friend; 20 | import org.jongo.query.Query; 21 | import org.jongo.util.JongoTestBase; 22 | import org.junit.Test; 23 | 24 | import static org.assertj.core.api.Assertions.assertThat; 25 | 26 | public class JongoTest extends JongoTestBase { 27 | 28 | @Test 29 | public void canObtainACollection() throws Exception { 30 | 31 | Jongo jongo = new Jongo(getDatabase()); 32 | 33 | MongoCollection collection = jongo.getCollection("collection-name"); 34 | 35 | assertThat(collection).isNotNull(); 36 | assertThat(collection.getName()).isEqualTo("collection-name"); 37 | } 38 | 39 | @Test 40 | public void canCreateQuery() throws Exception { 41 | 42 | Jongo jongo = new Jongo(getDatabase()); 43 | 44 | Query query = jongo.createQuery("{test:1}"); 45 | 46 | assertThat(query.toDBObject().get("test")).isEqualTo(1); 47 | } 48 | 49 | @Test 50 | public void canGetMapper() throws Exception { 51 | 52 | Jongo jongo = new Jongo(getDatabase()); 53 | 54 | Mapper mapper = jongo.getMapper(); 55 | 56 | assertThat(mapper).isNotNull(); 57 | assertThat(mapper.getMarshaller().marshall(new Friend("test"))).isNotNull(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/MongoCursorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCursor; 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | 23 | import java.util.Iterator; 24 | import java.util.NoSuchElementException; 25 | 26 | import static org.assertj.core.api.Assertions.assertThat; 27 | import static org.mockito.Mockito.*; 28 | 29 | public class MongoCursorTest { 30 | 31 | private DBCursor dbCursor; 32 | private MongoCursor mongoCursor; 33 | 34 | @Before 35 | public void setUp() throws Exception { 36 | dbCursor = mock(DBCursor.class); 37 | mongoCursor = new MongoCursor(dbCursor, mock(ResultHandler.class)); 38 | } 39 | 40 | @Test(expected = NoSuchElementException.class) 41 | public void shouldFailWhenNoMoreElements() throws Exception { 42 | 43 | when(dbCursor.hasNext()).thenReturn(false); 44 | 45 | mongoCursor.next(); 46 | } 47 | 48 | @Test 49 | public void shouldCloseDbCursor() throws Exception { 50 | 51 | mongoCursor.close(); 52 | 53 | verify(dbCursor).close(); 54 | } 55 | 56 | @Test 57 | public void shouldReturnACopyOfDbCursor() throws Exception { 58 | 59 | when(dbCursor.copy()).thenReturn(dbCursor); 60 | 61 | Iterator iterator = mongoCursor.iterator(); 62 | 63 | assertThat(iterator).isNotNull(); 64 | assert mongoCursor != iterator; 65 | verify(dbCursor).copy(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/NonPojoTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.fasterxml.jackson.databind.JsonNode; 20 | import com.fasterxml.jackson.databind.node.JsonNodeFactory; 21 | import com.fasterxml.jackson.databind.node.ObjectNode; 22 | import org.bson.types.ObjectId; 23 | import org.jongo.util.JongoTestBase; 24 | import org.junit.After; 25 | import org.junit.Before; 26 | import org.junit.Test; 27 | 28 | import java.util.HashMap; 29 | import java.util.Map; 30 | 31 | import static org.assertj.core.api.Assertions.assertThat; 32 | 33 | public class NonPojoTest extends JongoTestBase { 34 | 35 | private MongoCollection collection; 36 | 37 | @Before 38 | public void setUp() throws Exception { 39 | collection = createEmptyCollection("friends"); 40 | } 41 | 42 | @After 43 | public void tearDown() throws Exception { 44 | dropCollection("friends"); 45 | } 46 | 47 | @Test 48 | public void canSaveMapWithObjectId() throws Exception { 49 | ObjectId id = ObjectId.get(); 50 | Map map = new HashMap(); 51 | map.put("name", "John"); 52 | map.put("_id", id); 53 | 54 | collection.save(map); 55 | 56 | Map result = collection.findOne().as(Map.class); 57 | assertThat(result.get("_id")).isEqualTo(id); 58 | } 59 | 60 | @Test 61 | public void canSaveANewMap() throws Exception { 62 | Map map = new HashMap(); 63 | map.put("name", "John"); 64 | 65 | collection.save(map); 66 | 67 | Map result = collection.findOne().as(Map.class); 68 | assertThat(result.get("_id")).isNotNull(); 69 | } 70 | 71 | @Test 72 | public void canFindAndSaveMap() throws Exception { 73 | 74 | collection.insert("{name:'John'}"); 75 | Map map = collection.findOne().as(Map.class); 76 | map.put("name", "Robert"); 77 | 78 | collection.save(map); 79 | 80 | Map result = collection.findOne().as(Map.class); 81 | assertThat(result.get("name")).isEqualTo("Robert"); 82 | assertThat(result.get("_id")).isNotNull(); 83 | } 84 | 85 | @Test 86 | public void canSaveANewJsonNode() throws Exception { 87 | JsonNodeFactory factory = new JsonNodeFactory(false); 88 | ObjectNode node = factory.objectNode(); 89 | node.put("test", "value"); 90 | 91 | collection.save(node); 92 | 93 | JsonNode result = collection.findOne().as(JsonNode.class); 94 | assertThat(result.get("_id")).isNotNull(); 95 | assertThat(result.get("test").asText()).isEqualTo("value"); 96 | } 97 | 98 | @Test 99 | public void canFindAndSaveJsonNode() throws Exception { 100 | 101 | collection.insert("{name:'John'}"); 102 | ObjectNode node = collection.findOne().as(ObjectNode.class); 103 | node.put("name", "Robert"); 104 | 105 | collection.save(node); 106 | 107 | Map result = collection.findOne().as(Map.class); 108 | assertThat(result.get("name")).isEqualTo("Robert"); 109 | assertThat(result.get("_id")).isNotNull(); 110 | } 111 | } -------------------------------------------------------------------------------- /src/test/java/org/jongo/RemoveTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.WriteResult; 20 | import org.bson.types.ObjectId; 21 | import org.jongo.model.Friend; 22 | import org.jongo.util.JongoTestBase; 23 | import org.junit.After; 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | 29 | public class RemoveTest extends JongoTestBase { 30 | 31 | private MongoCollection collection; 32 | 33 | @Before 34 | public void setUp() throws Exception { 35 | collection = createEmptyCollection("friends"); 36 | } 37 | 38 | @After 39 | public void tearDown() throws Exception { 40 | dropCollection("friends"); 41 | } 42 | 43 | @Test 44 | public void canRemoveASpecificDocument() throws Exception { 45 | /* given */ 46 | collection.save(new Friend("John")); 47 | collection.save(new Friend("Peter")); 48 | 49 | /* when */ 50 | WriteResult writeResult = collection.remove("{name:'John'}"); 51 | 52 | /* then */ 53 | Iterable friends = collection.find().as(Friend.class); 54 | assertThat(friends).hasSize(1); 55 | assertThat(writeResult).isNotNull(); 56 | } 57 | 58 | @Test 59 | public void canRemoveByObjectId() throws Exception { 60 | /* given */ 61 | collection.insert("{ _id:{$oid:'47cc67093475061e3d95369d'}, name:'John'}"); 62 | 63 | /* when */ 64 | ObjectId id = new ObjectId("47cc67093475061e3d95369d"); 65 | WriteResult writeResult = collection.remove(id); 66 | 67 | /* then */ 68 | assertThat(writeResult).isNotNull(); 69 | Friend friend = collection.findOne().as(Friend.class); 70 | assertThat(friend).isNull(); 71 | } 72 | 73 | @Test 74 | public void canRemoveWithParameters() throws Exception { 75 | /* given */ 76 | collection.insert("{name:'John'}"); 77 | 78 | /* when */ 79 | WriteResult writeResult = collection.remove("{name:#}", "John"); 80 | 81 | /* then */ 82 | assertThat(writeResult).isNotNull(); 83 | Friend friend = collection.findOne().as(Friend.class); 84 | assertThat(friend).isNull(); 85 | } 86 | 87 | @Test 88 | public void canRemoveAll() throws Exception { 89 | /* given */ 90 | collection.insert("{name:'John'}"); 91 | collection.insert("{name:'Peter'}"); 92 | 93 | /* when */ 94 | WriteResult writeResult = collection.remove(); 95 | 96 | /* then */ 97 | assertThat(writeResult).isNotNull(); 98 | Friend friend = collection.findOne().as(Friend.class); 99 | assertThat(friend).isNull(); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/WriteConcernTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo; 18 | 19 | import com.mongodb.DBCollection; 20 | import com.mongodb.DBObject; 21 | import com.mongodb.WriteConcern; 22 | import org.jongo.model.Friend; 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | 26 | import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper; 27 | import static org.mockito.Matchers.eq; 28 | import static org.mockito.Mockito.*; 29 | 30 | public class WriteConcernTest { 31 | 32 | DBCollection mockedDBCollection = mock(DBCollection.class); 33 | private MongoCollection collection; 34 | 35 | @Before 36 | public void setUp() throws Exception { 37 | collection = new MongoCollection(mockedDBCollection, jacksonMapper().build()); 38 | } 39 | 40 | @Test 41 | public void shouldUseDefaultDriverWriteConcern() throws Exception { 42 | 43 | Friend john = new Friend("John"); 44 | 45 | collection.save(john); 46 | 47 | verify(mockedDBCollection).save(any(DBObject.class), isNull(WriteConcern.class)); 48 | } 49 | 50 | @Test 51 | public void canSaveWithCustomWriteConcernOnCollection() throws Exception { 52 | 53 | Friend john = new Friend("John"); 54 | 55 | collection.withWriteConcern(WriteConcern.ACKNOWLEDGED).save(john); 56 | 57 | verify(mockedDBCollection).save(any(DBObject.class), eq(WriteConcern.ACKNOWLEDGED)); 58 | } 59 | 60 | @Test 61 | public void canInsertWithCustomWriteConcernOnCollection() throws Exception { 62 | 63 | collection.withWriteConcern(WriteConcern.MAJORITY).insert("{name : 'Abby'}"); 64 | 65 | verify(mockedDBCollection).insert(any(DBObject.class), eq(WriteConcern.MAJORITY)); 66 | } 67 | 68 | @Test 69 | public void canUpdateWithCustomWriteConcernOnCollection() throws Exception { 70 | 71 | collection.withWriteConcern(WriteConcern.MAJORITY).update("{}").upsert().with("{$set:{name:'John'}}"); 72 | 73 | verify(mockedDBCollection).update(any(DBObject.class), any(DBObject.class), eq(true), eq(false), eq(WriteConcern.MAJORITY)); 74 | } 75 | 76 | @Test 77 | public void canRemoveWithCustomWriteConcernOnCollection() throws Exception { 78 | 79 | collection.withWriteConcern(WriteConcern.MAJORITY).remove(); 80 | 81 | verify(mockedDBCollection).remove(any(DBObject.class), eq(WriteConcern.MAJORITY)); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bench/BenchUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bench; 18 | 19 | import com.mongodb.*; 20 | import org.jongo.Jongo; 21 | import org.jongo.Mapper; 22 | import org.jongo.MongoCollection; 23 | import org.jongo.model.Coordinate; 24 | import org.jongo.model.Friend; 25 | 26 | import java.net.UnknownHostException; 27 | 28 | import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper; 29 | 30 | class BenchUtil { 31 | 32 | public static Friend createFriend(int id) { 33 | return new Friend("John" + id, "Address" + id, new Coordinate(1, id)); 34 | } 35 | 36 | public static DBObject asDBObject(Friend friend) { 37 | 38 | DBObject dbo = new BasicDBObject(); 39 | dbo.put("name", friend.getName()); 40 | dbo.put("address", friend.getAddress()); 41 | 42 | BasicDBObject coordinate = new BasicDBObject(); 43 | coordinate.put("lat", friend.getCoordinate().lat); 44 | coordinate.put("lng", friend.getCoordinate().lng); 45 | 46 | dbo.put("coordinate", coordinate); 47 | 48 | return dbo; 49 | } 50 | 51 | public static DBCollection getCollectionFromDriver() throws UnknownHostException { 52 | MongoClient nativeMongo = new MongoClient(); 53 | return nativeMongo.getDB("jongo").getCollection("benchmark"); 54 | } 55 | 56 | public static MongoCollection getCollectionFromJongo(Mapper mapper) throws UnknownHostException { 57 | MongoClient mongo = new MongoClient(); 58 | DB db = mongo.getDB("jongo"); 59 | Jongo jongo = new Jongo(db, mapper); 60 | return jongo.getCollection("benchmark"); 61 | } 62 | 63 | public static void injectFriendsIntoDB(int nbDocuments) throws UnknownHostException { 64 | MongoCollection collection = getCollectionFromJongo(jacksonMapper().build()); 65 | collection.drop(); 66 | for (int i = 0; i < nbDocuments; i++) { 67 | collection.withWriteConcern(WriteConcern.MAJORITY).save(createFriend(i)); 68 | } 69 | long count = collection.count(); 70 | if (count < nbDocuments) { 71 | throw new RuntimeException("Not enough documents have been saved into db : expected " + nbDocuments + "/ saved: " + count); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bench/FindBench.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bench; 18 | 19 | import com.google.caliper.Param; 20 | import com.google.caliper.Runner; 21 | import com.google.caliper.SimpleBenchmark; 22 | import com.mongodb.DBCollection; 23 | import com.mongodb.DBCursor; 24 | import com.mongodb.DBObject; 25 | import org.jongo.MongoCollection; 26 | import org.jongo.model.Coordinate; 27 | import org.jongo.model.Friend; 28 | 29 | import static org.jongo.bench.BenchUtil.getCollectionFromDriver; 30 | import static org.jongo.bench.BenchUtil.getCollectionFromJongo; 31 | import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper; 32 | 33 | public class FindBench extends SimpleBenchmark { 34 | 35 | private static final int NB_DOCUMENTS = 100000; 36 | @Param({"1"}) 37 | int size = 1; 38 | private MongoCollection bsonCollection; 39 | private DBCollection dbCollection; 40 | 41 | protected void setUp() throws Exception { 42 | bsonCollection = getCollectionFromJongo(jacksonMapper().build()); 43 | dbCollection = getCollectionFromDriver(); 44 | 45 | if (dbCollection.count() < NB_DOCUMENTS) { 46 | BenchUtil.injectFriendsIntoDB(NB_DOCUMENTS); 47 | } 48 | } 49 | 50 | public int timeDriverFind(int reps) { 51 | int insertions = 0; 52 | for (int i = 0; i < reps; i++) { 53 | DBCursor cursor = dbCollection.find().limit(size); 54 | for (DBObject dbo : cursor) { 55 | DBObject coord = (DBObject) dbo.get("coordinate"); 56 | Coordinate coordinate = new Coordinate((Integer) coord.get("lat"), (Integer) coord.get("lng")); 57 | Friend f = new Friend((String) dbo.get("name"), (String) dbo.get("address"), coordinate); 58 | insertions++; 59 | } 60 | } 61 | return insertions; 62 | } 63 | 64 | public int timeJongoFind(int reps) { 65 | int insertions = 0; 66 | for (int i = 0; i < reps; i++) { 67 | for (Friend friend : bsonCollection.find().limit(size).as(Friend.class)) { 68 | insertions++; 69 | } 70 | } 71 | return insertions; 72 | } 73 | 74 | public static void main(String[] args) { 75 | Runner.main(FindBench.class, new String[]{ 76 | //"--vm", "/opt/jvm/jdk1.6.0_37/bin/java,/opt/jvm/jdk1.7.0_10/bin/java", 77 | "-Dsize=1000,10000,50000,100000" 78 | }); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bench/SaveBench.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bench; 18 | 19 | import com.google.caliper.Param; 20 | import com.google.caliper.Runner; 21 | import com.google.caliper.SimpleBenchmark; 22 | import com.mongodb.DBCollection; 23 | import com.mongodb.WriteConcern; 24 | import org.jongo.MongoCollection; 25 | 26 | import static org.jongo.bench.BenchUtil.*; 27 | import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper; 28 | 29 | public class SaveBench extends SimpleBenchmark { 30 | 31 | @Param({"1"}) 32 | int size = 1; 33 | 34 | private DBCollection dbCollection; 35 | private MongoCollection bsonCollection; 36 | 37 | protected void setUp() throws Exception { 38 | 39 | bsonCollection = getCollectionFromJongo(jacksonMapper().build()).withWriteConcern(WriteConcern.MAJORITY); 40 | dbCollection = getCollectionFromDriver(); 41 | 42 | bsonCollection.drop(); 43 | } 44 | 45 | public void timeDriverSave(int reps) { 46 | for (int i = 0; i < reps; i++) { 47 | for (int j = 0; j < size; j++) { 48 | dbCollection.save(asDBObject(createFriend(reps + j))); 49 | } 50 | } 51 | } 52 | 53 | public void timeJongoSave(int reps) { 54 | for (int i = 0; i < reps; i++) { 55 | for (int j = 0; j < size; j++) { 56 | bsonCollection.save(createFriend(reps + j)); 57 | } 58 | } 59 | } 60 | 61 | public static void main(String[] args) { 62 | Runner.main(SaveBench.class, new String[]{ 63 | //"--vm", "/opt/jvm/jdk1.6.0_37/bin/java,/opt/jvm/jdk1.7.0_10/bin/java", 64 | "-Dsize=1000,10000,50000" 65 | }); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bench/YourkitBench.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bench; 18 | 19 | import org.junit.Ignore; 20 | import org.junit.Test; 21 | 22 | public class YourkitBench { 23 | 24 | private static int ITERATION = 100000; 25 | 26 | 27 | @Test 28 | @Ignore 29 | public void saveWithDriver() throws Exception { 30 | SaveBench saveBench = new SaveBench(); 31 | saveBench.setUp(); 32 | saveBench.timeDriverSave(ITERATION); 33 | } 34 | 35 | @Test 36 | @Ignore 37 | public void saveWithBsonJongo() throws Exception { 38 | SaveBench saveBench = new SaveBench(); 39 | saveBench.setUp(); 40 | saveBench.timeJongoSave(ITERATION); 41 | } 42 | 43 | @Test 44 | @Ignore 45 | public void findWithDriver() throws Exception { 46 | FindBench findBench = new FindBench(); 47 | findBench.setUp(); 48 | findBench.timeDriverFind(ITERATION); 49 | } 50 | 51 | @Test 52 | @Ignore 53 | public void findWithBsonJongo() throws Exception { 54 | FindBench findBench = new FindBench(); 55 | findBench.setUp(); 56 | findBench.timeJongoFind(ITERATION); 57 | } 58 | 59 | @Test 60 | @Ignore 61 | public void decodeWithBsonJongo() throws Exception { 62 | DecoderBench bench = new DecoderBench(); 63 | bench.timeDecodeWithBsonJongo(1); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bson/BsonDBEncoderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import com.mongodb.BasicDBObject; 20 | import com.mongodb.DBEncoder; 21 | import com.mongodb.LazyDBObject; 22 | import org.bson.io.BasicOutputBuffer; 23 | import org.junit.Test; 24 | 25 | import static org.assertj.core.api.Assertions.assertThat; 26 | 27 | public class BsonDBEncoderTest { 28 | 29 | @Test 30 | public void shouldPipeLazyDbObject() throws Exception { 31 | 32 | DBEncoder encoder = BsonDBEncoder.FACTORY.create(); 33 | BasicOutputBuffer buffer = new BasicOutputBuffer(); 34 | 35 | encoder.writeObject(buffer, new LazyDBObject(new byte[]{5, 0, 0, 0, 0}, null)); 36 | 37 | assertThat(buffer.toByteArray()).isEqualTo(new byte[]{5, 0, 0, 0, 0}); 38 | 39 | } 40 | 41 | @Test 42 | public void shouldEncodeDBObject() throws Exception { 43 | DBEncoder encoder = BsonDBEncoder.FACTORY.create(); 44 | BasicOutputBuffer buffer = new BasicOutputBuffer(); 45 | 46 | encoder.writeObject(buffer, new BasicDBObject()); 47 | 48 | assertThat(buffer.size()).isGreaterThan(0); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bson/LazyBsonDocumentTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import org.junit.Test; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | 23 | public class LazyBsonDocumentTest { 24 | 25 | @Test 26 | public void shouldUseBsonSize() throws Exception { 27 | LazyBsonDocument document = new LazyBsonDocument(new byte[]{6, 0, 0, 0, 0}); 28 | 29 | assertThat(document.getSize()).isEqualTo(6); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/bson/PrimitivesTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.bson; 18 | 19 | import org.junit.Test; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | 23 | public class PrimitivesTest { 24 | 25 | @Test 26 | public void shouldContainsClassAndSubclasses() throws Exception { 27 | assertThat(Primitives.contains(Number.class)).isTrue(); 28 | assertThat(Primitives.contains(Integer.class)).isTrue(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/marshall/jackson/JacksonEngineTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | import com.mongodb.DBObject; 20 | import org.jongo.bson.BsonDocument; 21 | import org.jongo.marshall.MarshallingException; 22 | import org.jongo.marshall.jackson.configuration.Mapping; 23 | import org.jongo.model.Fox; 24 | import org.jongo.model.Friend; 25 | import org.jongo.util.ErrorObject; 26 | import org.junit.Test; 27 | 28 | import java.io.IOException; 29 | 30 | import static junit.framework.Assert.fail; 31 | import static org.assertj.core.api.Assertions.assertThat; 32 | import static org.jongo.util.BsonUtil.bsonify; 33 | 34 | 35 | public class JacksonEngineTest { 36 | 37 | JacksonEngine engine = new JacksonEngine(new Mapping.Builder().build()); 38 | 39 | @Test(expected = MarshallingException.class) 40 | public void shouldFailWhenUnableToMarshall() throws Exception { 41 | 42 | engine.marshall(new ErrorObject()); 43 | } 44 | 45 | @Test 46 | public void shouldFailWhenUnableToUnmarshall() throws Exception { 47 | 48 | try { 49 | engine.unmarshall(bsonify("{'error':'notADate'}"), ErrorObject.class); 50 | fail(); 51 | } catch (Exception e) { 52 | assertThat(e).isInstanceOf(MarshallingException.class); 53 | } 54 | } 55 | 56 | @Test 57 | public void canMarshall() { 58 | 59 | BsonDocument doc = engine.marshall(new Fox("fantastic", "roux")); 60 | 61 | DBObject dbo = doc.toDBObject(); 62 | assertThat(dbo.get("_class")).isEqualTo("org.jongo.model.Fox"); 63 | assertThat(dbo.get("name")).isEqualTo("fantastic"); 64 | assertThat(dbo.get("color")).isEqualTo("roux"); 65 | } 66 | 67 | @Test 68 | public void canUnmarshallBson() throws IOException { 69 | 70 | BsonDocument document = bsonify("{'address': '22 rue des murlins'}"); 71 | 72 | Friend friend = engine.unmarshall(document, Friend.class); 73 | 74 | assertThat(friend.getAddress()).isEqualTo("22 rue des murlins"); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/marshall/jackson/JacksonViewTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | import com.mongodb.DBObject; 20 | import org.jongo.bson.BsonDocument; 21 | import org.jongo.marshall.jackson.configuration.Mapping; 22 | import org.jongo.model.Fox; 23 | import org.jongo.model.Views; 24 | import org.junit.Test; 25 | 26 | import static org.assertj.core.api.Assertions.assertThat; 27 | import static org.jongo.util.BsonUtil.bsonify; 28 | 29 | public class JacksonViewTest { 30 | 31 | private JacksonEngine createProcessorWithView(final Class viewClass) { 32 | Mapping mapping = new Mapping.Builder().withView(viewClass).build(); 33 | return new JacksonEngine(mapping); 34 | } 35 | 36 | @Test 37 | public void shouldRespectJsonPublicViewOnMarshall() throws Exception { 38 | 39 | JacksonEngine custom = createProcessorWithView(Views.Public.class); 40 | Fox vixen = new Fox("fantastic", "roux"); 41 | vixen.setGender("female"); 42 | 43 | BsonDocument doc = custom.marshall(vixen); 44 | 45 | DBObject result = doc.toDBObject(); 46 | assertThat(result.get("gender")).isNull(); 47 | assertThat(result.get("_class")).isEqualTo("org.jongo.model.Fox"); 48 | assertThat(result.get("name")).isEqualTo("fantastic"); 49 | assertThat(result.get("color")).isEqualTo("roux"); 50 | } 51 | 52 | @Test 53 | public void shouldRespectJsonPrivateViewOnMarshall() throws Exception { 54 | 55 | JacksonEngine custom = createProcessorWithView(Views.Private.class); 56 | Fox vixen = new Fox("fantastic", "roux"); 57 | vixen.setGender("female"); 58 | 59 | BsonDocument doc = custom.marshall(vixen); 60 | 61 | DBObject result = doc.toDBObject(); 62 | assertThat(result.get("_class")).isEqualTo("org.jongo.model.Fox"); 63 | assertThat(result.get("name")).isEqualTo("fantastic"); 64 | assertThat(result.get("color")).isEqualTo("roux"); 65 | assertThat(result.get("gender")).isEqualTo("female"); 66 | } 67 | 68 | @Test 69 | public void respectsJsonPublicViewOnUnmarshall() throws Exception { 70 | 71 | BsonDocument doc = bsonify("{'_class':'org.jongo.model.Fox','name':'fantastic','color':'roux','gender':'female'}"); 72 | JacksonEngine custom = createProcessorWithView(Views.Public.class); 73 | 74 | Fox fox = custom.unmarshall(doc, Fox.class); 75 | 76 | assertThat(fox.getGender()).isNull(); 77 | } 78 | 79 | @Test 80 | public void respectsJsonPrivateViewOnUnmarshall() throws Exception { 81 | 82 | BsonDocument doc = bsonify("{'_class':'org.jongo.model.Fox','name':'fantastic','color':'roux','gender':'female'}"); 83 | JacksonEngine custom = createProcessorWithView(Views.Private.class); 84 | 85 | Fox fox = custom.unmarshall(doc, Fox.class); 86 | 87 | assertThat(fox.getGender()).isEqualTo("female"); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/marshall/jackson/ParameterBindingWithJacksonTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson; 18 | 19 | 20 | import com.fasterxml.jackson.annotation.JsonValue; 21 | import org.jongo.MongoCollection; 22 | import org.jongo.util.JongoTestBase; 23 | import org.junit.Before; 24 | import org.junit.Test; 25 | 26 | import java.util.Map; 27 | 28 | import static org.assertj.core.api.Assertions.assertThat; 29 | 30 | public class ParameterBindingWithJacksonTest extends JongoTestBase { 31 | 32 | private MongoCollection collection; 33 | 34 | @Before 35 | public void setUp() throws Exception { 36 | collection = createEmptyCollection("marshalling"); 37 | } 38 | 39 | @Test 40 | public void canBindEnumWithJsonValue() throws Exception { 41 | 42 | collection.insert("{'type':0}"); 43 | 44 | Map result = collection.findOne("{'type':#}", Type.EMPTY).as(Map.class); 45 | 46 | assertThat(result).isNotNull(); 47 | } 48 | 49 | @Test 50 | public void canBindStringWithJsonValue() throws Exception { 51 | 52 | collection.insert("{'prefixer':'prefix_data'}"); 53 | 54 | Map result = collection.findOne("{'prefixer':#}", new StringWithPrefix("data")).as(Map.class); 55 | 56 | assertThat(result).isNotNull(); 57 | } 58 | 59 | private static enum Type { 60 | EMPTY(0); 61 | 62 | private int value; 63 | 64 | private Type(int value) { 65 | this.value = value; 66 | } 67 | 68 | @JsonValue 69 | public int getValue() { 70 | return value; 71 | } 72 | 73 | } 74 | 75 | private static class StringWithPrefix { 76 | 77 | private final String value; 78 | 79 | private StringWithPrefix(String value) { 80 | this.value = value; 81 | } 82 | 83 | @JsonValue 84 | public String getValue() { 85 | return "prefix_" + value; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/marshall/jackson/configuration/MappingTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.configuration; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import org.bson.types.ObjectId; 21 | import org.jongo.model.Friend; 22 | import org.junit.Test; 23 | 24 | import java.io.StringWriter; 25 | import java.io.Writer; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | 29 | public class MappingTest { 30 | 31 | @Test 32 | public void shouldNotAddBsonConfWithCustomMapper() throws Exception { 33 | Mapping.Builder builder = new Mapping.Builder(new ObjectMapper()); 34 | Mapping mapping = builder.build(); 35 | ObjectId id = ObjectId.get();//serialized using bson serializer 36 | Friend friend = new Friend(id, "John"); 37 | 38 | Writer writer = new StringWriter(); 39 | mapping.getWriter(friend).writeValue(writer, friend); 40 | 41 | assertThat(writer.toString()).contains("John"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/marshall/jackson/oid/AnnotationsTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.marshall.jackson.oid; 18 | 19 | import com.fasterxml.jackson.annotation.JsonProperty; 20 | import com.fasterxml.jackson.databind.JsonMappingException; 21 | import com.fasterxml.jackson.databind.ObjectMapper; 22 | import com.fasterxml.jackson.databind.ObjectReader; 23 | import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; 24 | import com.mongodb.BasicDBObject; 25 | import com.mongodb.DBObject; 26 | import org.jongo.bson.Bson; 27 | import org.jongo.bson.BsonDocument; 28 | import org.jongo.marshall.jackson.configuration.Mapping; 29 | import org.junit.Before; 30 | import org.junit.Test; 31 | 32 | import java.io.IOException; 33 | 34 | import static org.hamcrest.CoreMatchers.equalTo; 35 | import static org.junit.Assert.assertThat; 36 | 37 | 38 | public class AnnotationsTest { 39 | 40 | private ObjectMapper externalMapper; 41 | 42 | @Before 43 | public void setUp() throws Exception { 44 | externalMapper = new ObjectMapper(); 45 | } 46 | 47 | @Test(expected = UnrecognizedPropertyException.class) 48 | public void shouldIgnoreIdAnnotation() throws IOException { 49 | externalMapper.readValue("{\"_id\":\"53a499be60b2a2248d956875\"}", WithMongoId.class); 50 | } 51 | 52 | @Test 53 | public void shouldHandleIdAnnotation() throws IOException { 54 | 55 | Mapping build = new Mapping.Builder().build(); 56 | ObjectReader reader = build.getReader(WithMongoId.class); 57 | BsonDocument document = Bson.createDocument(new BasicDBObject("_id", "53a499be60b2a2248d956875")); 58 | 59 | WithMongoId friend = reader.readValue(document.toByteArray()); 60 | 61 | assertThat(friend.id, equalTo("53a499be60b2a2248d956875")); 62 | } 63 | 64 | 65 | @Test(expected = JsonMappingException.class) 66 | public void shouldIgnoreObjectIdAnnotation() throws IOException { 67 | externalMapper.readValue("{\"id\":{\"$oid\":\"53a499be60b2a2248d956875\"}}", WithMongoObjectId.class); 68 | } 69 | 70 | @Test 71 | public void shouldHandleObjectIdAnnotation() throws IOException { 72 | 73 | Mapping build = new Mapping.Builder().build(); 74 | ObjectReader reader = build.getReader(WithMongoObjectId.class); 75 | DBObject oid = new BasicDBObject("$oid", "53a499be60b2a2248d956875"); 76 | BasicDBObject dbObject = new BasicDBObject("id", oid); 77 | BsonDocument document = Bson.createDocument(dbObject); 78 | 79 | WithMongoObjectId testObj = reader.readValue(document.toByteArray()); 80 | 81 | assertThat(testObj.id, equalTo("53a499be60b2a2248d956875")); 82 | } 83 | 84 | private static class WithMongoObjectId { 85 | @MongoObjectId 86 | @JsonProperty 87 | String id; 88 | } 89 | 90 | private static class WithMongoId { 91 | @MongoId 92 | private String id; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Animal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import com.fasterxml.jackson.annotation.JsonTypeInfo; 20 | import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; 21 | import org.bson.types.ObjectId; 22 | 23 | @JsonTypeInfo(use = Id.CLASS, property = "_class") 24 | public class Animal { 25 | 26 | ObjectId _id; 27 | String name; 28 | 29 | Animal() { 30 | } 31 | 32 | public Animal(String name) { 33 | this.name = name; 34 | } 35 | 36 | public ObjectId getId() { 37 | return _id; 38 | } 39 | 40 | public String getName() { 41 | return name; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Article.java: -------------------------------------------------------------------------------- 1 | package org.jongo.model; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | public final class Article { 7 | 8 | private String title; 9 | @SuppressWarnings("unused") 10 | private String author; 11 | private List tags; 12 | 13 | public Article(String title, String author, String... tags) { 14 | this.title = title; 15 | this.author = author; 16 | this.tags = Arrays.asList(tags); 17 | } 18 | 19 | private Article() { 20 | //used by jackson 21 | } 22 | 23 | public String getTitle() { 24 | return title; 25 | } 26 | 27 | public String getAuthor() { 28 | return author; 29 | } 30 | 31 | public List getTags() { 32 | return tags; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Coordinate.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | 20 | public class Coordinate { 21 | 22 | public int lat, lng; 23 | 24 | Coordinate() { 25 | } 26 | 27 | public Coordinate(int lat, int lng) { 28 | this.lat = lat; 29 | this.lng = lng; 30 | } 31 | 32 | @Override 33 | public boolean equals(Object o) { 34 | if (this == o) return true; 35 | if (!(o instanceof Coordinate)) return false; 36 | 37 | Coordinate that = (Coordinate) o; 38 | 39 | if (lat != that.lat) return false; 40 | if (lng != that.lng) return false; 41 | 42 | return true; 43 | } 44 | 45 | @Override 46 | public int hashCode() { 47 | int result = lat; 48 | result = 31 * result + lng; 49 | return result; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/ExposableFriend.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import com.google.common.base.Objects; 20 | import org.jongo.marshall.jackson.oid.Id; 21 | import org.jongo.marshall.jackson.oid.MongoId; 22 | import org.jongo.marshall.jackson.oid.MongoObjectId; 23 | import org.jongo.marshall.jackson.oid.ObjectId; 24 | 25 | public class ExposableFriend { 26 | 27 | @Id //see DeprecatedAnnotationsCompatibilitySuiteTest for more informations 28 | @ObjectId //see DeprecatedAnnotationsCompatibilitySuiteTest for more informations 29 | @MongoId 30 | @MongoObjectId 31 | private String id; 32 | private String name; 33 | 34 | private ExposableFriend() { 35 | //jackson 36 | } 37 | 38 | public ExposableFriend(String id, String name) { 39 | this.id = id; 40 | this.name = name; 41 | } 42 | 43 | public ExposableFriend(String name) { 44 | this.name = name; 45 | } 46 | 47 | public String getId() { 48 | return id; 49 | } 50 | 51 | public String getName() { 52 | return name; 53 | } 54 | 55 | public void setName(String name) { 56 | this.name = name; 57 | } 58 | 59 | public boolean equals(Object o) { 60 | if (o == null || !(o instanceof ExposableFriend)) return false; 61 | ExposableFriend ef = (ExposableFriend) o; 62 | 63 | return Objects.equal(id, ef.id) && 64 | Objects.equal(name, ef.name); 65 | } 66 | 67 | public String toString() { 68 | return Objects.toStringHelper(this) 69 | .add("id", id) 70 | .add("name", name) 71 | .toString(); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/ExternalFriend.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import org.jongo.marshall.jackson.oid.Id; 20 | import org.jongo.marshall.jackson.oid.MongoId; 21 | 22 | public class ExternalFriend { 23 | 24 | @Id //see DeprecatedAnnotationsCompatibilitySuiteTest for more informations 25 | @MongoId 26 | private String id; 27 | private String name; 28 | 29 | private ExternalFriend() { 30 | //jackson 31 | } 32 | 33 | public ExternalFriend(String id, String name) { 34 | this.id = id; 35 | this.name = name; 36 | } 37 | 38 | public String getId() { 39 | return id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | public static ExternalFriend createFriendWithoutId(String name) { 51 | ExternalFriend friend = new ExternalFriend(); 52 | friend.setName(name); 53 | return friend; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Fox.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import com.fasterxml.jackson.annotation.JsonView; 20 | 21 | public class Fox extends Animal { 22 | String color; 23 | 24 | @JsonView(Views.Private.class) 25 | String gender; 26 | 27 | Fox() { 28 | } 29 | 30 | public Fox(String name, String color) { 31 | super(name); 32 | this.color = color; 33 | } 34 | 35 | public void setGender(String gender) { 36 | this.gender = gender; 37 | } 38 | 39 | public String getGender() { 40 | return gender; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Friend.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import org.bson.types.ObjectId; 20 | import org.jongo.marshall.jackson.oid.Id; 21 | import org.jongo.marshall.jackson.oid.MongoId; 22 | 23 | public class Friend { 24 | 25 | @Id //see DeprecatedAnnotationsCompatibilitySuiteTest for more informations 26 | @MongoId 27 | private ObjectId id; 28 | private String name; 29 | private String address; 30 | private Coordinate coordinate; 31 | private Gender gender; 32 | 33 | public Friend(String name) { 34 | this.name = name; 35 | } 36 | 37 | public Friend(ObjectId id, String name) { 38 | this.id = id; 39 | this.name = name; 40 | } 41 | 42 | public Friend(String name, String address) { 43 | this.name = name; 44 | this.address = address; 45 | } 46 | 47 | public Friend(String name, Coordinate coordinate) { 48 | this.name = name; 49 | this.coordinate = coordinate; 50 | } 51 | 52 | public Friend() { 53 | } 54 | 55 | public Friend(String name, String address, Coordinate coordinate) { 56 | this.name = name; 57 | this.address = address; 58 | this.coordinate = coordinate; 59 | } 60 | 61 | public ObjectId getId() { 62 | return id; 63 | } 64 | 65 | public String getName() { 66 | return name; 67 | } 68 | 69 | public String getAddress() { 70 | return address; 71 | } 72 | 73 | public void setAddress(String address) { 74 | this.address = address; 75 | } 76 | 77 | public Coordinate getCoordinate() { 78 | return coordinate; 79 | } 80 | 81 | public void setCoordinate(Coordinate coordinate) { 82 | this.coordinate = coordinate; 83 | } 84 | 85 | @Override 86 | public boolean equals(Object o) { 87 | if (this == o) return true; 88 | if (!(o instanceof Friend)) return false; 89 | 90 | Friend friend = (Friend) o; 91 | 92 | if (address != null ? !address.equals(friend.address) : friend.address != null) return false; 93 | if (coordinate != null ? !coordinate.equals(friend.coordinate) : friend.coordinate != null) return false; 94 | if (id != null ? !id.equals(friend.id) : friend.id != null) return false; 95 | if (name != null ? !name.equals(friend.name) : friend.name != null) return false; 96 | 97 | return true; 98 | } 99 | 100 | @Override 101 | public int hashCode() { 102 | int result = id != null ? id.hashCode() : 0; 103 | result = 31 * result + (name != null ? name.hashCode() : 0); 104 | result = 31 * result + (address != null ? address.hashCode() : 0); 105 | result = 31 * result + (coordinate != null ? coordinate.hashCode() : 0); 106 | return result; 107 | } 108 | 109 | public void setGender(Gender gender) { 110 | this.gender = gender; 111 | } 112 | 113 | public Gender getGender() { 114 | return gender; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Gender.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | public enum Gender { 20 | FEMALE 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/LinkedFriend.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import org.bson.types.ObjectId; 20 | 21 | public class LinkedFriend extends Friend { 22 | ObjectId friendRelationId; 23 | 24 | LinkedFriend() { 25 | } 26 | 27 | public LinkedFriend(ObjectId friendRelationId) { 28 | this.friendRelationId = friendRelationId; 29 | } 30 | 31 | public ObjectId getRelationId() { 32 | return friendRelationId; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/MapReduceData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import org.jongo.marshall.jackson.oid.Id; 20 | 21 | import java.util.Date; 22 | 23 | /** 24 | * A class that is shaped like results from map reduce operations. 25 | * 26 | * @author Christian Trimble 27 | */ 28 | public class MapReduceData { 29 | 30 | public static class Key { 31 | protected String group; 32 | protected Date date; 33 | 34 | public Key() { 35 | } 36 | 37 | public Key(String group, Date date) { 38 | this.group = group; 39 | this.date = date; 40 | } 41 | 42 | public String getGroup() { 43 | return group; 44 | } 45 | 46 | public void setGroup(String group) { 47 | this.group = group; 48 | } 49 | 50 | public Date getDate() { 51 | return date; 52 | } 53 | 54 | public void setDate(Date date) { 55 | this.date = date; 56 | } 57 | } 58 | 59 | public static class Value { 60 | protected int count; 61 | 62 | public Value() { 63 | } 64 | 65 | public Value(int count) { 66 | this.count = count; 67 | } 68 | 69 | public int getCount() { 70 | return count; 71 | } 72 | 73 | public void setCount(int count) { 74 | this.count = count; 75 | } 76 | } 77 | 78 | @Id 79 | protected Key id; 80 | protected Value value; 81 | 82 | public MapReduceData() { 83 | } 84 | 85 | public MapReduceData(String group, Date date, int count) { 86 | this.id = new Key(group, date); 87 | this.value = new Value(count); 88 | } 89 | 90 | public Key getId() { 91 | return id; 92 | } 93 | 94 | public void setId(Key id) { 95 | this.id = id; 96 | } 97 | 98 | public Value getValue() { 99 | return value; 100 | } 101 | 102 | public void setValue(Value value) { 103 | this.value = value; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/TypeWithNested.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | import org.jongo.marshall.jackson.oid.MongoObjectId; 20 | 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | public class TypeWithNested { 25 | public static class NestedDocument { 26 | private String name; 27 | private String value; 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public NestedDocument withName(String name) { 38 | this.name = name; 39 | return this; 40 | } 41 | 42 | public String getValue() { 43 | return value; 44 | } 45 | 46 | public void setValue(String value) { 47 | this.value = value; 48 | } 49 | 50 | public NestedDocument withValue(String value) { 51 | this.value = value; 52 | return this; 53 | } 54 | } 55 | 56 | @MongoObjectId 57 | private String id; 58 | private List nested = new ArrayList(); 59 | 60 | public String getId() { 61 | return id; 62 | } 63 | 64 | public void setId(String id) { 65 | this.id = id; 66 | } 67 | 68 | public TypeWithNested withId(String id) { 69 | this.id = id; 70 | return this; 71 | } 72 | 73 | public List getNested() { 74 | return nested; 75 | } 76 | 77 | public void setNested(List nested) { 78 | this.nested = nested; 79 | } 80 | 81 | public TypeWithNested addNested(NestedDocument nested) { 82 | this.nested.add(nested); 83 | return this; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/model/Views.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.model; 18 | 19 | /** 20 | * A collection of Jackson marker views for testing. These classes are used to annotate properties 21 | * as being part of a particular view using @JsonView(ViewName.class) 22 | * 23 | * @author mark 24 | */ 25 | public class Views { 26 | public static class Public { 27 | } 28 | 29 | public static class Private extends Public { 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/query/QueryTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.query; 18 | 19 | import com.mongodb.DBObject; 20 | import org.jongo.marshall.jackson.JacksonEngine; 21 | import org.jongo.marshall.jackson.configuration.Mapping; 22 | import org.junit.Test; 23 | 24 | import static org.assertj.core.api.Assertions.assertThat; 25 | 26 | public class QueryTest { 27 | 28 | @Test 29 | public void shouldConvertToDBObject() throws Exception { 30 | 31 | Query query = new BsonQueryFactory(new JacksonEngine(Mapping.defaultMapping())).createQuery("{'value':1}"); 32 | 33 | DBObject dbObject = query.toDBObject(); 34 | 35 | assertThat(dbObject.containsField("value")).isTrue(); 36 | assertThat(dbObject.get("value")).isEqualTo(1); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/spike/MarshallingListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.spike; 18 | 19 | public interface MarshallingListener { 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/spike/MongoDumpTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.spike; 18 | 19 | import com.fasterxml.jackson.databind.MappingIterator; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.ObjectReader; 22 | import com.mongodb.WriteConcern; 23 | import de.undercouch.bson4jackson.BsonFactory; 24 | import org.bson.BSONObject; 25 | import org.bson.BasicBSONObject; 26 | import org.jongo.MongoCollection; 27 | import org.jongo.util.JongoTestBase; 28 | import org.junit.After; 29 | import org.junit.Before; 30 | import org.junit.Test; 31 | 32 | import java.io.InputStream; 33 | 34 | import static org.assertj.core.api.Assertions.assertThat; 35 | 36 | public class MongoDumpTest extends JongoTestBase { 37 | 38 | private MongoCollection collection; 39 | 40 | @Before 41 | public void setUp() throws Exception { 42 | collection = createEmptyCollection("friends"); 43 | } 44 | 45 | @After 46 | public void tearDown() throws Exception { 47 | dropCollection("friends"); 48 | } 49 | 50 | @Test 51 | public void importBsonDumpFileIntoCollection() throws Exception { 52 | 53 | InputStream bsonDump = getClass().getClassLoader().getResourceAsStream("1000friends.bson"); 54 | BsonFactory bsonFactory = new BsonFactory(); 55 | //bsonFactory.enable(BsonParser.Feature.HONOR_DOCUMENT_LENGTH); // fails when enabled 56 | ObjectReader reader = new ObjectMapper(bsonFactory).reader(BasicBSONObject.class); 57 | 58 | MappingIterator iterator = reader.readValues(bsonDump); 59 | try { 60 | while (iterator.hasNext()) { 61 | BSONObject bsonObject = iterator.next(); 62 | collection.withWriteConcern(WriteConcern.MAJORITY).save(bsonObject); 63 | } 64 | } finally { 65 | iterator.close(); 66 | } 67 | 68 | assertThat(collection.count()).isEqualTo(1000); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/spike/projection/JacksonProjection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.spike.projection; 18 | 19 | import com.fasterxml.jackson.databind.JsonNode; 20 | import com.fasterxml.jackson.databind.ObjectMapper; 21 | import com.fasterxml.jackson.databind.jsonschema.JsonSchema; 22 | import com.fasterxml.jackson.databind.node.ObjectNode; 23 | import com.mongodb.BasicDBObject; 24 | import com.mongodb.DBObject; 25 | import com.mongodb.MongoClient; 26 | import org.bson.BsonDocument; 27 | import org.bson.BsonDocumentWrapper; 28 | import org.jongo.query.Query; 29 | 30 | import java.util.Iterator; 31 | import java.util.Map; 32 | 33 | public class JacksonProjection implements Projection { 34 | 35 | private final ObjectMapper mapper; 36 | 37 | public JacksonProjection(ObjectMapper mapper) { 38 | this.mapper = mapper; 39 | } 40 | 41 | public Query getProjectionQuery(Class pojoClass) { 42 | DBObject query = new BasicDBObject(); 43 | putFieldNames(query, getSchemaNode(pojoClass)); 44 | query.removeField("_id"); 45 | return new ProjectionQuery(query); 46 | } 47 | 48 | private ObjectNode getSchemaNode(Class pojoClass) { 49 | try { 50 | JsonSchema schema = mapper.generateJsonSchema(pojoClass); 51 | return schema.getSchemaNode(); 52 | } catch (Exception e) { 53 | throw new RuntimeException("Unable to createLazyDBObject field DBObject for class: " + pojoClass, e); 54 | } 55 | } 56 | 57 | private void putFieldNames(DBObject dbo, JsonNode node) { 58 | JsonNode properties = node.get("properties"); 59 | Iterator> fields = properties.fields(); 60 | while (fields.hasNext()) { 61 | Map.Entry field = fields.next(); 62 | String fieldName = field.getKey(); 63 | JsonNode value = field.getValue(); 64 | if (value.has("properties")) { 65 | BasicDBObject children = new BasicDBObject(); 66 | putFieldNames(children, value); 67 | dbo.put(fieldName, children); 68 | } else { 69 | dbo.put(fieldName, 1); 70 | } 71 | } 72 | } 73 | 74 | private static class ProjectionQuery implements Query { 75 | 76 | private final DBObject dbo; 77 | 78 | private ProjectionQuery(DBObject dbo) { 79 | this.dbo = dbo; 80 | } 81 | 82 | public DBObject toDBObject() { 83 | return dbo; 84 | } 85 | 86 | public BsonDocument toBsonDocument() { 87 | return BsonDocumentWrapper.asBsonDocument(dbo, MongoClient.getDefaultCodecRegistry()); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/spike/projection/JacksonProjectionTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.spike.projection; 18 | 19 | import com.fasterxml.jackson.annotation.JsonIgnore; 20 | import com.mongodb.DBObject; 21 | import org.jongo.marshall.jackson.configuration.Mapping; 22 | import org.jongo.model.Coordinate; 23 | import org.jongo.model.Fox; 24 | import org.jongo.model.Friend; 25 | import org.junit.Before; 26 | import org.junit.Test; 27 | 28 | import static org.assertj.core.api.Assertions.assertThat; 29 | 30 | public class JacksonProjectionTest { 31 | 32 | private JacksonProjection projection; 33 | 34 | @Before 35 | public void setUp() throws Exception { 36 | Mapping mapping = new Mapping.Builder().build(); 37 | projection = new JacksonProjection(mapping.getObjectMapper()); 38 | } 39 | 40 | @Test 41 | public void canCreateQueryForPOJO() throws Exception { 42 | 43 | DBObject fields = projection.getProjectionQuery(Friend.class).toDBObject(); 44 | 45 | assertThat(sanitize(fields.toString())) 46 | .isEqualTo("{\"name\":1,\"address\":1,\"coordinate\":{\"lat\":1,\"lng\":1},\"gender\":1}"); 47 | } 48 | 49 | @Test 50 | public void canCreateQueryForPOJOWithSuperType() throws Exception { 51 | 52 | DBObject fields = projection.getProjectionQuery(Fox.class).toDBObject(); 53 | 54 | assertThat(sanitize(fields.toString())).isEqualTo("{\"name\":1,\"color\":1,\"gender\":1}"); 55 | } 56 | 57 | @Test 58 | public void shouldHonorJacksonAnnotations() throws Exception { 59 | 60 | DBObject fields = projection.getProjectionQuery(HiddenCoordinate.class).toDBObject(); 61 | 62 | assertThat(sanitize(fields.toString())).isEqualTo("{\"lng\":1}"); 63 | } 64 | 65 | @Test(expected = RuntimeException.class) 66 | public void shouldFailWhenUnableToCreateFieldsDBO() throws Exception { 67 | 68 | projection.getProjectionQuery(Object.class); 69 | } 70 | 71 | private String sanitize(String value) { 72 | return value.replaceAll(" ", ""); 73 | } 74 | 75 | private static class HiddenCoordinate extends Coordinate { 76 | 77 | 78 | @JsonIgnore 79 | public int lat; 80 | 81 | private HiddenCoordinate(int lat, int lng) { 82 | super(lat, lng); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/spike/projection/Projection.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.spike.projection; 18 | 19 | import org.jongo.query.Query; 20 | 21 | public interface Projection { 22 | 23 | Query getProjectionQuery(Class clazz); 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/util/BsonUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.util; 18 | 19 | import com.fasterxml.jackson.databind.ObjectMapper; 20 | import com.mongodb.BasicDBObject; 21 | import com.mongodb.DBObject; 22 | import org.jongo.bson.Bson; 23 | import org.jongo.bson.BsonDocument; 24 | 25 | import java.io.IOException; 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | public class BsonUtil { 30 | 31 | public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); 32 | 33 | public static BsonDocument bsonify(String json) throws IOException { 34 | Map map = OBJECT_MAPPER.readValue(jsonify(json), HashMap.class); 35 | DBObject dbo = new BasicDBObject(); 36 | dbo.putAll(map); 37 | return Bson.createDocument(dbo); 38 | } 39 | 40 | public static String jsonify(String json) { 41 | return json.replace("'", "\""); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/util/ErrorObject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.util; 18 | 19 | import com.fasterxml.jackson.annotation.JsonProperty; 20 | 21 | import java.util.Date; 22 | 23 | public class ErrorObject { 24 | 25 | private Date error; 26 | 27 | @JsonProperty 28 | public Date getError() { 29 | throw new RuntimeException(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/util/IdResultHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.util; 18 | 19 | import com.mongodb.DBObject; 20 | import org.jongo.ResultHandler; 21 | 22 | public class IdResultHandler implements ResultHandler { 23 | 24 | public String map(DBObject result) { 25 | return result.get("_id").toString(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/util/JongoTestBase.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.util; 18 | 19 | import com.mongodb.CommandResult; 20 | import com.mongodb.DB; 21 | import org.jongo.Jongo; 22 | import org.jongo.Mapper; 23 | import org.jongo.MongoCollection; 24 | import org.junit.BeforeClass; 25 | 26 | import java.net.UnknownHostException; 27 | 28 | import static org.jongo.marshall.jackson.JacksonMapper.Builder.jacksonMapper; 29 | import static org.junit.Assume.assumeTrue; 30 | 31 | public abstract class JongoTestBase { 32 | 33 | private static MongoResource MONGO_RESOURCE; 34 | 35 | private Jongo jongo; 36 | private Mapper mapper; 37 | 38 | public JongoTestBase() { 39 | this(jacksonMapper().build()); 40 | } 41 | 42 | protected JongoTestBase(Mapper mapper) { 43 | configure(mapper); 44 | } 45 | 46 | public void configure(Mapper mapper) { 47 | this.mapper = mapper; 48 | this.jongo = new Jongo(MONGO_RESOURCE.getDb("test_jongo"), mapper); 49 | } 50 | 51 | @BeforeClass 52 | public static void startMongo() throws Exception { 53 | MONGO_RESOURCE = new MongoResource(); 54 | } 55 | 56 | protected MongoCollection createEmptyCollection(String collectionName) { 57 | MongoCollection col = jongo.getCollection(collectionName); 58 | col.drop(); 59 | return col; 60 | } 61 | 62 | protected void dropCollection(String collectionName) { 63 | getDatabase().getCollection(collectionName).drop(); 64 | } 65 | 66 | protected DB getDatabase() { 67 | return jongo.getDatabase(); 68 | } 69 | 70 | protected Jongo getJongo() { 71 | return jongo; 72 | } 73 | 74 | protected Mapper getMapper() { 75 | return mapper; 76 | } 77 | 78 | protected void assumeThatMongoVersionIsGreaterThan(String expectedVersion) throws UnknownHostException { 79 | int expectedVersionAsInt = Integer.valueOf(expectedVersion.replaceAll("\\.", "")); 80 | CommandResult buildInfo = getDatabase().command("buildInfo"); 81 | String version = (String) buildInfo.get("version"); 82 | int currentVersion = Integer.valueOf(version.replaceAll("\\.", "")); 83 | assumeTrue(currentVersion >= expectedVersionAsInt); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/util/MongoEmbeddedRule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.util; 18 | 19 | import org.junit.rules.TestRule; 20 | import org.junit.runner.Description; 21 | import org.junit.runners.model.Statement; 22 | 23 | /** 24 | * A JUnit rule for testing with embedded Mongo. 25 | * 26 | * @author Alexandre Dutra 27 | * @author Christian Trimble 28 | */ 29 | public class MongoEmbeddedRule implements TestRule { 30 | private MongoResource mongoResource; 31 | 32 | public Statement apply(final Statement base, Description description) { 33 | return new Statement() { 34 | @Override 35 | public void evaluate() throws Throwable { 36 | mongoResource = new MongoResource(); 37 | base.evaluate(); 38 | } 39 | }; 40 | } 41 | 42 | public MongoResource getResource() { 43 | return mongoResource; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/org/jongo/util/compatibility/TestContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Benoît GUÉROUT and Yves AMSELLEM 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.jongo.util.compatibility; 18 | 19 | import org.jongo.Mapper; 20 | import org.jongo.util.JongoTestBase; 21 | import org.reflections.Reflections; 22 | 23 | import java.util.*; 24 | 25 | public class TestContext { 26 | 27 | private final String contextName; 28 | private final Mapper mapper; 29 | private final List> ignoredTestCases; 30 | private final Map, String> ignoredTests; 31 | 32 | public TestContext(String contextName, Mapper mapper) { 33 | this.contextName = contextName; 34 | this.mapper = mapper; 35 | this.ignoredTestCases = new ArrayList>(); 36 | this.ignoredTests = new HashMap, String>(); 37 | } 38 | 39 | public String getContextName() { 40 | return contextName; 41 | } 42 | 43 | public Mapper getMapper() { 44 | return mapper; 45 | } 46 | 47 | public boolean mustIgnoreTestCase(Class clazz) { 48 | return ignoredTestCases.contains(clazz); 49 | } 50 | 51 | public void ignoreTestCase(Class clazz) { 52 | ignoredTestCases.add(clazz); 53 | } 54 | 55 | public boolean mustIgnoreTest(Class clazz, String methodName) { 56 | return ignoredTests.containsKey(clazz) && ignoredTests.get(clazz).equals(methodName); 57 | } 58 | 59 | public void ignoreTest(Class clazz, String methodName) { 60 | ignoredTests.put(clazz, methodName); 61 | } 62 | 63 | public List> findTestCases() { 64 | Set> jongoTestCases = new Reflections("org.jongo").getSubTypesOf(JongoTestBase.class); 65 | return new ArrayList>(jongoTestCases); 66 | } 67 | 68 | public void prepareTestCase(Object testCase) throws Exception { 69 | if (testCase instanceof JongoTestBase) { 70 | JongoTestBase currentTestCase = (JongoTestBase) testCase; 71 | currentTestCase.configure(mapper); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/test/resources/1000friends.bson: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bguerout/jongo/1f0aed9ac1a4a331642204ae57f5b64e8ac90b6b/src/test/resources/1000friends.bson -------------------------------------------------------------------------------- /src/test/sh/compatibility/jackson-versions-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | function run_tests() { 6 | local jackson_version=${1} 7 | local output_dir=${2} 8 | 9 | echo "Running tests against jackson ${jackson_version}" 10 | mvn verify \ 11 | -Djackson.version="${jackson_version}" \ 12 | -DreportFormat=plain \ 13 | -DuseFile=false \ 14 | -Dmaven.source.skip=true \ 15 | -Dmaven.javadoc.skip=true \ 16 | --log-file "${output_dir}/build-jackson-${jackson_version}.log" 17 | } 18 | 19 | function main() { 20 | local output_dir="./target/jongo-compatibility" 21 | 22 | mkdir -p "./target/jongo-compatibility" 23 | 24 | run_tests "2.7.0" "${output_dir}" 25 | run_tests "2.7.1" "${output_dir}" 26 | run_tests "2.7.2" "${output_dir}" 27 | run_tests "2.7.3" "${output_dir}" 28 | run_tests "2.7.4" "${output_dir}" 29 | run_tests "2.7.5" "${output_dir}" 30 | run_tests "2.7.6" "${output_dir}" 31 | run_tests "2.7.7" "${output_dir}" 32 | run_tests "2.7.8" "${output_dir}" 33 | run_tests "2.7.9" "${output_dir}" 34 | run_tests "2.8.0" "${output_dir}" 35 | run_tests "2.8.1" "${output_dir}" 36 | run_tests "2.8.10" "${output_dir}" 37 | run_tests "2.8.11" "${output_dir}" 38 | run_tests "2.8.2" "${output_dir}" 39 | run_tests "2.8.3" "${output_dir}" 40 | run_tests "2.8.4" "${output_dir}" 41 | run_tests "2.8.5" "${output_dir}" 42 | run_tests "2.8.6" "${output_dir}" 43 | run_tests "2.8.7" "${output_dir}" 44 | run_tests "2.8.8" "${output_dir}" 45 | run_tests "2.8.9" "${output_dir}" 46 | run_tests "2.9.0" "${output_dir}" 47 | run_tests "2.9.1" "${output_dir}" 48 | run_tests "2.9.2" "${output_dir}" 49 | run_tests "2.9.3" "${output_dir}" 50 | run_tests "2.9.4" "${output_dir}" 51 | run_tests "2.9.5" "${output_dir}" 52 | run_tests "2.9.6" "${output_dir}" 53 | run_tests "2.9.7" "${output_dir}" 54 | run_tests "2.9.8" "${output_dir}" 55 | run_tests "2.9.9" "${output_dir}" 56 | run_tests "2.9.10" "${output_dir}" 57 | run_tests "2.10.0" "${output_dir}" 58 | run_tests "2.10.1" "${output_dir}" 59 | run_tests "2.10.2" "${output_dir}" 60 | run_tests "2.10.3" "${output_dir}" 61 | run_tests "2.10.4" "${output_dir}" 62 | run_tests "2.10.5" "${output_dir}" 63 | run_tests "2.11.0" "${output_dir}" 64 | run_tests "2.11.1" "${output_dir}" 65 | run_tests "2.11.2" "${output_dir}" 66 | run_tests "2.11.3" "${output_dir}" 67 | run_tests "2.11.4" "${output_dir}" 68 | run_tests "2.12.0" "${output_dir}" 69 | run_tests "2.12.1" "${output_dir}" 70 | } 71 | 72 | main "$@" 73 | -------------------------------------------------------------------------------- /src/test/sh/compatibility/mongodb-versions-tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | function run_tests() { 6 | local mongo_driver_legacy_version=${1} 7 | local mongodb_version=${2} 8 | local output_dir=${3} 9 | 10 | echo "Running tests against mongo-driver-legacy ${mongo_driver_legacy_version} and MongoDB ${mongodb_version}" 11 | mvn verify \ 12 | -Dmongo-driver-legacy.version="${mongo_driver_legacy_version}" \ 13 | -Dembedmongo.version="${mongodb_version}" \ 14 | -DreportFormat=plain \ 15 | -DuseFile=false \ 16 | -Dmaven.source.skip=true \ 17 | -Dmaven.javadoc.skip=true \ 18 | --log-file "${output_dir}/build-driver-$mongo_driver_legacy_version-db-$mongodb_version.log" 19 | } 20 | 21 | function main() { 22 | local output_dir="./target/jongo-compatibility" 23 | 24 | mkdir -p "./target/jongo-compatibility" 25 | 26 | run_tests "4.0.6" "3.4.15" "${output_dir}" 27 | run_tests "4.0.6" "3.5.5" "${output_dir}" 28 | run_tests "4.0.6" "3.6.5" "${output_dir}" 29 | run_tests "4.0.6" "4.0.12" "${output_dir}" 30 | #run_tests "4.0.6" "4.4.1" "${output_dir}" 31 | #see https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo/issues/326 32 | 33 | run_tests "4.1.2" "3.4.15" "${output_dir}" 34 | run_tests "4.1.2" "3.5.5" "${output_dir}" 35 | run_tests "4.1.2" "3.6.5" "${output_dir}" 36 | run_tests "4.1.2" "4.0.12" "${output_dir}" 37 | #run_tests "4.1.2" "4.4.1" "${output_dir}" 38 | 39 | run_tests "4.2.1" "3.4.15" "${output_dir}" 40 | run_tests "4.2.1" "3.5.5" "${output_dir}" 41 | run_tests "4.2.1" "3.6.5" "${output_dir}" 42 | run_tests "4.2.1" "4.0.12" "${output_dir}" 43 | #run_tests "4.2.1" "4.4.1" "${output_dir}" 44 | } 45 | 46 | main "$@" 47 | -------------------------------------------------------------------------------- /src/test/sh/test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 6 | 7 | bash "${SCRIPT_DIR}/compatibility/jackson-versions-tests.sh" 8 | bash "${SCRIPT_DIR}/compatibility/mongodb-versions-tests.sh" 9 | --------------------------------------------------------------------------------