diff --git a/.gitignore b/.gitignore index d98238c..f51edc4 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ *.ipr *.iws target/ +.idea/ \ No newline at end of file diff --git a/src/main/java/org/codinjutsu/tools/nosql/DatabaseVendorClientManager.java b/src/main/java/org/codinjutsu/tools/nosql/DatabaseVendorClientManager.java index a8e6ad6..f667a9f 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/DatabaseVendorClientManager.java +++ b/src/main/java/org/codinjutsu/tools/nosql/DatabaseVendorClientManager.java @@ -21,7 +21,7 @@ import org.codinjutsu.tools.nosql.commons.logic.DatabaseClient; import org.codinjutsu.tools.nosql.commons.model.DatabaseServer; import org.codinjutsu.tools.nosql.couchbase.logic.CouchbaseClient; -import org.codinjutsu.tools.nosql.mongo.logic.MongoClient; +import org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient; import org.codinjutsu.tools.nosql.redis.logic.RedisClient; import java.util.HashMap; @@ -32,7 +32,7 @@ public class DatabaseVendorClientManager { private static final Map> dataClientByVendor = new HashMap<>(); static { - dataClientByVendor.put(DatabaseVendor.MONGO, MongoClient.class); + dataClientByVendor.put(DatabaseVendor.MONGO, SingleMongoClient.class); dataClientByVendor.put(DatabaseVendor.REDIS, RedisClient.class); dataClientByVendor.put(DatabaseVendor.COUCHBASE, CouchbaseClient.class); } diff --git a/src/main/java/org/codinjutsu/tools/nosql/NoSqlExplorerPanel.java b/src/main/java/org/codinjutsu/tools/nosql/NoSqlExplorerPanel.java index ca31a2c..09b0f75 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/NoSqlExplorerPanel.java +++ b/src/main/java/org/codinjutsu/tools/nosql/NoSqlExplorerPanel.java @@ -32,7 +32,6 @@ import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ui.tree.TreeUtil; import org.codinjutsu.tools.nosql.commons.logic.ConfigurationException; -import org.codinjutsu.tools.nosql.commons.logic.DatabaseClient; import org.codinjutsu.tools.nosql.commons.model.Database; import org.codinjutsu.tools.nosql.commons.model.DatabaseServer; import org.codinjutsu.tools.nosql.commons.utils.GuiUtils; @@ -44,9 +43,9 @@ import org.codinjutsu.tools.nosql.commons.view.editor.NoSqlDatabaseObjectFile; import org.codinjutsu.tools.nosql.couchbase.model.CouchbaseDatabase; import org.codinjutsu.tools.nosql.couchbase.view.editor.CouchbaseObjectFile; -import org.codinjutsu.tools.nosql.mongo.logic.MongoClient; -import org.codinjutsu.tools.nosql.mongo.model.MongoCollection; -import org.codinjutsu.tools.nosql.mongo.model.MongoDatabase; +import org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoCollection; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoDatabase; import org.codinjutsu.tools.nosql.mongo.view.action.DropCollectionAction; import org.codinjutsu.tools.nosql.mongo.view.action.DropDatabaseAction; import org.codinjutsu.tools.nosql.mongo.view.editor.MongoObjectFile; @@ -179,9 +178,9 @@ public void run() { private void addDatabasesIfAny(DatabaseServer databaseServer, DefaultMutableTreeNode serverNode) { for (Database database : databaseServer.getDatabases()) { DefaultMutableTreeNode databaseNode = new DefaultMutableTreeNode(database); - if (database instanceof MongoDatabase) { - MongoDatabase mongoDatabase = (MongoDatabase) database; - for (MongoCollection collection : mongoDatabase.getCollections()) { + if (database instanceof SingleMongoDatabase) { + SingleMongoDatabase singleMongoDatabase = (SingleMongoDatabase) database; + for (SingleMongoCollection collection : singleMongoDatabase.getCollections()) { databaseNode.add(new DefaultMutableTreeNode(collection)); } } @@ -272,7 +271,7 @@ public void mouseClicked(MouseEvent mouseEvent) { if (treeNode.getUserObject() instanceof DatabaseServer && treeNode.getChildCount() == 0) { reloadServerConfiguration(getSelectedServerNode(), true); } - if (treeNode.getUserObject() instanceof MongoCollection) { + if (treeNode.getUserObject() instanceof SingleMongoCollection) { loadRecords(); } if (treeNode.getUserObject() instanceof RedisDatabase) { @@ -304,7 +303,7 @@ public DefaultMutableTreeNode getSelectedServerNode() { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) databaseTree.getLastSelectedPathComponent(); if (treeNode != null) { Object userObject = treeNode.getUserObject(); - if (userObject instanceof MongoCollection) { + if (userObject instanceof SingleMongoCollection) { return (DefaultMutableTreeNode) treeNode.getParent().getParent(); } @@ -324,7 +323,7 @@ private DefaultMutableTreeNode getSelectedDatabaseNode() { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) databaseTree.getLastSelectedPathComponent(); if (treeNode != null) { Object userObject = treeNode.getUserObject(); -// if (userObject instanceof MongoCollection) { +// if (userObject instanceof SingleMongoCollection) { // return (DefaultMutableTreeNode) treeNode.getParent(); // } @@ -340,7 +339,7 @@ private DefaultMutableTreeNode getSelectedCollectionNode() { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) databaseTree.getLastSelectedPathComponent(); if (treeNode != null) { Object userObject = treeNode.getUserObject(); - if (userObject instanceof MongoCollection) { + if (userObject instanceof SingleMongoCollection) { return treeNode; } } @@ -384,28 +383,28 @@ public CouchbaseDatabase getSelectedCouchaseDatabase() { return (CouchbaseDatabase) database; } - public MongoDatabase getSelectedMongoDatabase() { + public SingleMongoDatabase getSelectedMongoDatabase() { DefaultMutableTreeNode databaseNode = getSelectedDatabaseNode(); if (databaseNode == null) { return null; } Object database = databaseNode.getUserObject(); - if (!(database instanceof MongoDatabase)) { + if (!(database instanceof SingleMongoDatabase)) { return null; } - return (MongoDatabase) databaseNode.getUserObject(); + return (SingleMongoDatabase) databaseNode.getUserObject(); } - public MongoCollection getSelectedCollection() { + public SingleMongoCollection getSelectedCollection() { DefaultMutableTreeNode collectionNode = getSelectedCollectionNode(); if (collectionNode == null) { return null; } - return (MongoCollection) collectionNode.getUserObject(); + return (SingleMongoCollection) collectionNode.getUserObject(); } public void loadRecords() { @@ -424,13 +423,13 @@ private NoSqlDatabaseObjectFile createNoSqlObjectFile() { // TODO need to put in } public void dropCollection() {// TODO need to put in a customizer - MongoClient databaseClient = (MongoClient) databaseVendorClientManager.get(DatabaseVendor.MONGO); + SingleMongoClient databaseClient = (SingleMongoClient) databaseVendorClientManager.get(DatabaseVendor.MONGO); databaseClient.dropCollection(getConfiguration(), getSelectedCollection()); reloadServerConfiguration(getSelectedServerNode(), true); } public void dropDatabase() {// TODO need to put in a customizer - MongoClient databaseClient = (MongoClient) databaseVendorClientManager.get(DatabaseVendor.MONGO); + SingleMongoClient databaseClient = (SingleMongoClient) databaseVendorClientManager.get(DatabaseVendor.MONGO); databaseClient.dropDatabase(getConfiguration(), getSelectedMongoDatabase()); reloadServerConfiguration(getSelectedServerNode(), true); } diff --git a/src/main/java/org/codinjutsu/tools/nosql/NoSqlTreeRenderer.java b/src/main/java/org/codinjutsu/tools/nosql/NoSqlTreeRenderer.java index 95d67eb..89ae454 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/NoSqlTreeRenderer.java +++ b/src/main/java/org/codinjutsu/tools/nosql/NoSqlTreeRenderer.java @@ -23,7 +23,7 @@ import org.codinjutsu.tools.nosql.commons.model.Database; import org.codinjutsu.tools.nosql.commons.model.DatabaseServer; import org.codinjutsu.tools.nosql.commons.utils.GuiUtils; -import org.codinjutsu.tools.nosql.mongo.model.MongoCollection; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoCollection; import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -57,9 +57,9 @@ public void customizeCellRenderer(@NotNull JTree mongoTree, Object value, boolea Database noSqlDatabase = (Database) userObject; append(noSqlDatabase.getName()); setIcon(DATABASE); - } else if (userObject instanceof MongoCollection) { - MongoCollection mongoCollection = (MongoCollection) userObject; - append(mongoCollection.getName()); + } else if (userObject instanceof SingleMongoCollection) { + SingleMongoCollection singleMongoCollection = (SingleMongoCollection) userObject; + append(singleMongoCollection.getName()); setIcon(MONGO_COLLECTION); } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUI.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUI.java index 05368f5..9d8846c 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUI.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUI.java @@ -21,7 +21,7 @@ import org.codinjutsu.tools.nosql.commons.view.AuthenticationView; import org.codinjutsu.tools.nosql.commons.view.NoSqlResultView; import org.codinjutsu.tools.nosql.commons.view.editor.NoSqlDatabaseObjectFile; -import org.codinjutsu.tools.nosql.mongo.logic.MongoClient; +import org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient; import org.codinjutsu.tools.nosql.mongo.view.MongoAuthenticationPanel; import org.codinjutsu.tools.nosql.mongo.view.MongoPanel; import org.codinjutsu.tools.nosql.mongo.view.editor.MongoObjectFile; @@ -38,7 +38,7 @@ public AuthenticationView createAythenticationView() { public NoSqlResultView createResultPanel(Project project, NoSqlDatabaseObjectFile objectFile) { MongoObjectFile mongoObjectFile = (MongoObjectFile) objectFile; return new MongoPanel(project, - MongoClient.getInstance(project), + SingleMongoClient.getInstance(project), mongoObjectFile.getConfiguration(), mongoObjectFile.getCollection()); } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUtils.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUtils.java index c5279ec..829823b 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUtils.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/MongoUtils.java @@ -16,15 +16,26 @@ package org.codinjutsu.tools.nosql.mongo; +import org.bson.Document; import org.codinjutsu.tools.nosql.ServerConfiguration; -import org.codinjutsu.tools.nosql.mongo.model.MongoDatabase; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoDatabase; public class MongoUtils { private MongoUtils() { } - public static String buildMongoUrl(ServerConfiguration serverConfiguration, MongoDatabase database) { + public static Object parseJSON(String json) { + // todo: hacky, but works for now. + // Need to find a better way to do this + if (json.startsWith("[")) { + return Document.parse("{'x':" + json + "}").get("x"); + } + + return Document.parse(json); + } + + public static String buildMongoUrl(ServerConfiguration serverConfiguration, SingleMongoDatabase database) { return String.format("%s/%s", serverConfiguration.getServerUrl(), database == null ? "test" : database.getName()); } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClient.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClient.java similarity index 59% rename from src/main/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClient.java rename to src/main/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClient.java index d2af7f6..40b814e 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClient.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClient.java @@ -18,10 +18,16 @@ import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.project.Project; -import com.mongodb.*; -import com.mongodb.client.MongoIterable; +import com.mongodb.Block; +import com.mongodb.MongoClient; +import com.mongodb.MongoClientURI; +import com.mongodb.MongoException; +import com.mongodb.client.*; +import com.mongodb.client.model.Filters; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; +import org.bson.Document; +import org.bson.conversions.Bson; import org.codinjutsu.tools.nosql.DatabaseVendor; import org.codinjutsu.tools.nosql.ServerConfiguration; import org.codinjutsu.tools.nosql.commons.logic.ConfigurationException; @@ -29,26 +35,29 @@ import org.codinjutsu.tools.nosql.commons.model.AuthenticationSettings; import org.codinjutsu.tools.nosql.commons.model.Database; import org.codinjutsu.tools.nosql.commons.model.DatabaseServer; -import org.codinjutsu.tools.nosql.mongo.model.MongoCollection; -import org.codinjutsu.tools.nosql.mongo.model.MongoDatabase; import org.codinjutsu.tools.nosql.mongo.model.MongoQueryOptions; import org.codinjutsu.tools.nosql.mongo.model.MongoResult; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoCollection; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoDatabase; import java.io.IOException; import java.net.UnknownHostException; -import java.util.*; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; -public class MongoClient implements DatabaseClient { +public class SingleMongoClient implements DatabaseClient { - private static final Logger LOG = Logger.getLogger(MongoClient.class); + private static final Logger LOG = Logger.getLogger(SingleMongoClient.class); private final List databaseServers = new LinkedList<>(); - public static MongoClient getInstance(Project project) { - return ServiceManager.getService(project, MongoClient.class); + public static SingleMongoClient getInstance(Project project) { + return ServiceManager.getService(project, SingleMongoClient.class); } public void connect(ServerConfiguration configuration) { - com.mongodb.MongoClient mongo = null; + MongoClient mongo = null; try { String userDatabase = configuration.getUserDatabase(); mongo = createMongoClient(configuration); @@ -101,7 +110,7 @@ public void loadServer(DatabaseServer databaseServer) { } List loadDatabaseCollections(ServerConfiguration configuration) { - com.mongodb.MongoClient mongo = null; + MongoClient mongo = null; List mongoDatabases = new LinkedList<>(); try { String userDatabase = configuration.getUserDatabase(); @@ -109,15 +118,21 @@ List loadDatabaseCollections(ServerConfiguration configuration) { mongo = createMongoClient(configuration); if (StringUtils.isNotEmpty(userDatabase)) { - DB database = mongo.getDB(userDatabase); + MongoDatabase database = mongo.getDatabase(userDatabase); mongoDatabases.add(createMongoDatabaseAndItsCollections(database)); } else { - List databaseNames = mongo.getDatabaseNames(); - Collections.sort(databaseNames); + MongoIterable databaseNames = mongo.listDatabaseNames(); for (String databaseName : databaseNames) { - DB database = mongo.getDB(databaseName); + MongoDatabase database = mongo.getDatabase(databaseName); mongoDatabases.add(createMongoDatabaseAndItsCollections(database)); } + + Collections.sort(mongoDatabases, new Comparator() { + @Override + public int compare(Database o1, Database o2) { + return o1.getName().compareTo(o2.getName()); + } + }); } return mongoDatabases; @@ -130,27 +145,32 @@ List loadDatabaseCollections(ServerConfiguration configuration) { } } - private MongoDatabase createMongoDatabaseAndItsCollections(DB database) { - MongoDatabase mongoDatabase = new MongoDatabase(database.getName()); + private SingleMongoDatabase createMongoDatabaseAndItsCollections(MongoDatabase database) { + SingleMongoDatabase singleMongoDatabase = new SingleMongoDatabase(database.getName()); - Set collectionNames = database.getCollectionNames(); + MongoIterable collectionNames = database.listCollectionNames(); for (String collectionName : collectionNames) { - mongoDatabase.addCollection(new MongoCollection(collectionName, database.getName())); + singleMongoDatabase.addCollection(new SingleMongoCollection(collectionName, database.getName())); } - return mongoDatabase; + return singleMongoDatabase; } - public void update(ServerConfiguration configuration, MongoCollection mongoCollection, DBObject mongoDocument) { - com.mongodb.MongoClient mongo = null; + public void update(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection, Document mongoDocument) { + MongoClient mongo = null; try { - String databaseName = mongoCollection.getDatabaseName(); + String databaseName = singleMongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); - DB database = mongo.getDB(databaseName); - DBCollection collection = database.getCollection(mongoCollection.getName()); + MongoDatabase database = mongo.getDatabase(databaseName); + MongoCollection collection = database.getCollection(singleMongoCollection.getName()); - collection.save(mongoDocument); + final Object id = mongoDocument.get("_id"); + if (id == null) { + collection.insertOne(mongoDocument); + } else { + collection.replaceOne(Filters.eq("_id", id), mongoDocument); + } } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { @@ -160,16 +180,15 @@ public void update(ServerConfiguration configuration, MongoCollection mongoColle } } - public void delete(ServerConfiguration configuration, MongoCollection mongoCollection, Object _id) { - com.mongodb.MongoClient mongo = null; + public void delete(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection, Object _id) { + MongoClient mongo = null; try { - String databaseName = mongoCollection.getDatabaseName(); + String databaseName = singleMongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); - DB database = mongo.getDB(databaseName); - DBCollection collection = database.getCollection(mongoCollection.getName()); - - collection.remove(new BasicDBObject("_id", _id)); + MongoDatabase database = mongo.getDatabase(databaseName); + MongoCollection collection = database.getCollection(singleMongoCollection.getName()); + collection.deleteOne(Filters.eq("_id", _id)); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { @@ -179,16 +198,16 @@ public void delete(ServerConfiguration configuration, MongoCollection mongoColle } } - public void dropCollection(ServerConfiguration configuration, MongoCollection mongoCollection) { - com.mongodb.MongoClient mongo = null; + public void dropCollection(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection) { + MongoClient mongo = null; try { - String databaseName = mongoCollection.getDatabaseName(); + String databaseName = singleMongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); - DB database = mongo.getDB(databaseName); - DBCollection collection = database.getCollection(mongoCollection.getName()); + mongo.getDatabase(databaseName) + .getCollection(singleMongoCollection.getName()) + .drop(); - collection.drop(); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { @@ -198,8 +217,8 @@ public void dropCollection(ServerConfiguration configuration, MongoCollection mo } } - public void dropDatabase(ServerConfiguration configuration, MongoDatabase selectedDatabase) { - com.mongodb.MongoClient mongo = null; + public void dropDatabase(ServerConfiguration configuration, SingleMongoDatabase selectedDatabase) { + MongoClient mongo = null; try { mongo = createMongoClient(configuration); mongo.dropDatabase(selectedDatabase.getName()); @@ -212,16 +231,17 @@ public void dropDatabase(ServerConfiguration configuration, MongoDatabase select } } - public MongoResult loadCollectionValues(ServerConfiguration configuration, MongoCollection mongoCollection, MongoQueryOptions mongoQueryOptions) { - com.mongodb.MongoClient mongo = null; + public MongoResult loadCollectionValues(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection, MongoQueryOptions mongoQueryOptions) { + MongoClient mongo = null; try { - String databaseName = mongoCollection.getDatabaseName(); + String databaseName = singleMongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); - DB database = mongo.getDB(databaseName); - DBCollection collection = database.getCollection(mongoCollection.getName()); + MongoDatabase database = mongo.getDatabase(databaseName); + + MongoCollection collection = database.getCollection(singleMongoCollection.getName()); - MongoResult mongoResult = new MongoResult(mongoCollection.getName()); + MongoResult mongoResult = new MongoResult(singleMongoCollection.getName()); if (mongoQueryOptions.isAggregate()) { return aggregate(mongoQueryOptions, mongoResult, collection); } @@ -237,16 +257,15 @@ public MongoResult loadCollectionValues(ServerConfiguration configuration, Mongo } } - public DBObject findMongoDocument(ServerConfiguration configuration, MongoCollection mongoCollection, Object _id) { - com.mongodb.MongoClient mongo = null; + public Document findMongoDocument(ServerConfiguration configuration, SingleMongoCollection singleMongoCollection, Object _id) { + MongoClient mongo = null; try { - String databaseName = mongoCollection.getDatabaseName(); + String databaseName = singleMongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); - DB database = mongo.getDB(databaseName); - DBCollection collection = database.getCollection(mongoCollection.getName()); - return collection.findOne(new BasicDBObject("_id", _id)); - + MongoDatabase database = mongo.getDatabase(databaseName); + com.mongodb.client.MongoCollection collection = database.getCollection(singleMongoCollection.getName()); + return collection.find(Filters.eq("_id", _id)).first(); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { @@ -256,45 +275,47 @@ public DBObject findMongoDocument(ServerConfiguration configuration, MongoCollec } } - private MongoResult aggregate(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult, DBCollection collection) { - AggregationOutput aggregate = collection.aggregate(mongoQueryOptions.getOperations()); + private MongoResult aggregate(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult, MongoCollection collection) { + AggregateIterable aggregate = collection.aggregate(mongoQueryOptions.getOperations()); + aggregate.useCursor(true); + int index = 0; - Iterator iterator = aggregate.results().iterator(); + MongoCursor iterator = aggregate.iterator(); while (iterator.hasNext() && index < mongoQueryOptions.getResultLimit()) { mongoResult.add(iterator.next()); } return mongoResult; } - private MongoResult find(MongoQueryOptions mongoQueryOptions, MongoResult mongoResult, DBCollection collection) { - DBObject filter = mongoQueryOptions.getFilter(); - DBObject projection = mongoQueryOptions.getProjection(); - DBObject sort = mongoQueryOptions.getSort(); + private MongoResult find(MongoQueryOptions mongoQueryOptions, final MongoResult mongoResult, MongoCollection collection) { + Bson filter = mongoQueryOptions.getFilter(); + Bson projection = mongoQueryOptions.getProjection(); + Bson sort = mongoQueryOptions.getSort(); - DBCursor cursor; + FindIterable findIterable; if (projection == null) { - cursor = collection.find(filter); + findIterable = collection.find(filter); } else { - cursor = collection.find(filter, projection); + findIterable = collection.find(filter).projection(projection); } if (sort != null) { - cursor = cursor.sort(sort); + findIterable = findIterable.sort(sort); } - try { - int index = 0; - while (cursor.hasNext() && index < mongoQueryOptions.getResultLimit()) { - mongoResult.add(cursor.next()); - index++; + findIterable.limit(mongoQueryOptions.getResultLimit()); + + findIterable.forEach(new Block() { + @Override + public void apply(Document document) { + mongoResult.add(document); } - } finally { - cursor.close(); - } + }); + return mongoResult; } - private com.mongodb.MongoClient createMongoClient(ServerConfiguration configuration) throws UnknownHostException { + private MongoClient createMongoClient(ServerConfiguration configuration) throws UnknownHostException { String serverUrl = configuration.getServerUrl(); if (StringUtils.isEmpty(serverUrl)) { throw new ConfigurationException("server host is not set"); @@ -317,7 +338,7 @@ private com.mongodb.MongoClient createMongoClient(ServerConfiguration configurat uriBuilder.sslEnabled(); } - return new com.mongodb.MongoClient(new MongoClientURI(uriBuilder.build())); + return new MongoClient(new MongoClientURI(uriBuilder.build())); } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoQueryOptions.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoQueryOptions.java index c96061f..4179ec6 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoQueryOptions.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoQueryOptions.java @@ -16,11 +16,12 @@ package org.codinjutsu.tools.nosql.mongo.model; -import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; import com.mongodb.util.JSON; import org.apache.commons.lang.StringUtils; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.codinjutsu.tools.nosql.mongo.MongoUtils; import java.util.LinkedList; import java.util.List; @@ -30,11 +31,11 @@ public class MongoQueryOptions { private static final int DEFAULT_RESULT_LIMIT = 300; private static final BasicDBObject EMPTY_FILTER = new BasicDBObject(); - private final List operations = new LinkedList(); + private final List operations = new LinkedList<>(); - private DBObject filter = EMPTY_FILTER; - private DBObject projection = null; - private DBObject sort; + private Bson filter = EMPTY_FILTER; + private Bson projection = null; + private Bson sort; private int resultLimit = DEFAULT_RESULT_LIMIT; @@ -42,44 +43,45 @@ public boolean isAggregate() { return !operations.isEmpty(); } - public List getOperations() { + public List getOperations() { return operations; } public void setOperations(String aggregateQuery) { operations.clear(); - BasicDBList operations = (BasicDBList) JSON.parse(aggregateQuery); + List operations = (List)MongoUtils.parseJSON(aggregateQuery); + //noinspection unchecked - safe to ignore - it parses it to a List this.operations.addAll(operations); } public void setFilter(String query) { if (!StringUtils.isBlank(query)) { - filter = (DBObject) JSON.parse(query); + filter = (Bson) JSON.parse(query); } } - public DBObject getFilter() { + public Bson getFilter() { return filter; } public void setProjection(String query) { if (!StringUtils.isBlank(query)) { - projection = (DBObject) JSON.parse(query); + projection = (Bson) JSON.parse(query); } } - public DBObject getProjection() { + public Bson getProjection() { return projection; } public void setSort(String query) { if (!StringUtils.isBlank(query)) { - sort = (DBObject) JSON.parse(query); + sort = (Bson) JSON.parse(query); } } - public DBObject getSort() { + public Bson getSort() { return sort; } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoResult.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoResult.java index 4707657..d781e41 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoResult.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoResult.java @@ -16,7 +16,7 @@ package org.codinjutsu.tools.nosql.mongo.model; -import com.mongodb.DBObject; +import org.bson.Document; import java.util.LinkedList; import java.util.List; @@ -24,17 +24,17 @@ public class MongoResult { private final String collectionName; - private final List mongoObjects = new LinkedList(); + private final List mongoObjects = new LinkedList<>(); public MongoResult(String collectionName) { this.collectionName = collectionName; } - public void add(DBObject dbObject) { + public void add(Document dbObject) { mongoObjects.add(dbObject); } - public List getMongoObjects() { + public List getMongoObjects() { return mongoObjects; } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoCollection.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/SingleMongoCollection.java similarity index 82% rename from src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoCollection.java rename to src/main/java/org/codinjutsu/tools/nosql/mongo/model/SingleMongoCollection.java index 756e955..3a066b5 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoCollection.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/SingleMongoCollection.java @@ -18,12 +18,12 @@ import org.jetbrains.annotations.NotNull; -public class MongoCollection implements Comparable { +public class SingleMongoCollection implements Comparable { private final String name; private final String databaseName; - public MongoCollection(String name, String databaseName) { + public SingleMongoCollection(String name, String databaseName) { this.name = name; this.databaseName = databaseName; } @@ -37,7 +37,7 @@ public String getDatabaseName() { } @Override - public int compareTo(@NotNull MongoCollection otherCollection) { + public int compareTo(@NotNull SingleMongoCollection otherCollection) { return this.name.compareTo(otherCollection.getName()); } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoDatabase.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/SingleMongoDatabase.java similarity index 70% rename from src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoDatabase.java rename to src/main/java/org/codinjutsu/tools/nosql/mongo/model/SingleMongoDatabase.java index 75cdd6f..fa71f19 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/model/MongoDatabase.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/model/SingleMongoDatabase.java @@ -22,11 +22,11 @@ import java.util.SortedSet; import java.util.TreeSet; -public class MongoDatabase extends Database { +public class SingleMongoDatabase extends Database { - private final SortedSet collections = new TreeSet(); + private final SortedSet collections = new TreeSet(); - public MongoDatabase(String name) { + public SingleMongoDatabase(String name) { super(name); } @@ -34,11 +34,11 @@ public String getName() { return name; } - public Set getCollections() { + public Set getCollections() { return collections; } - public void addCollection(MongoCollection mongoCollection) { - collections.add(mongoCollection); + public void addCollection(SingleMongoCollection singleMongoCollection) { + collections.add(singleMongoCollection); } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoCommandLineState.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoCommandLineState.java index 382c676..251259d 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoCommandLineState.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoCommandLineState.java @@ -28,7 +28,7 @@ import org.apache.commons.lang.StringUtils; import org.codinjutsu.tools.nosql.ServerConfiguration; import org.codinjutsu.tools.nosql.mongo.MongoUtils; -import org.codinjutsu.tools.nosql.mongo.model.MongoDatabase; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoDatabase; import org.jetbrains.annotations.NotNull; class MongoCommandLineState extends CommandLineState { @@ -56,7 +56,7 @@ private GeneralCommandLine generateCommandLine() { commandLine.setExePath(exePath); ServerConfiguration serverConfiguration = mongoRunConfiguration.getServerConfiguration(); - MongoDatabase database = mongoRunConfiguration.getDatabase(); + SingleMongoDatabase database = mongoRunConfiguration.getDatabase(); commandLine.addParameter(MongoUtils.buildMongoUrl(serverConfiguration, database)); VirtualFile scriptPath = mongoRunConfiguration.getScriptPath(); diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoRunConfiguration.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoRunConfiguration.java index 3b45fd5..e55c3ce 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoRunConfiguration.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/runner/MongoRunConfiguration.java @@ -35,7 +35,7 @@ import org.codinjutsu.tools.nosql.DatabaseVendor; import org.codinjutsu.tools.nosql.NoSqlConfiguration; import org.codinjutsu.tools.nosql.ServerConfiguration; -import org.codinjutsu.tools.nosql.mongo.model.MongoDatabase; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoDatabase; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -49,7 +49,7 @@ class MongoRunConfiguration extends ModuleBasedConfiguration mongoServers = MongoClient.getInstance(project).getServers(); - List availableMongoServers = new LinkedList(); + List mongoServers = SingleMongoClient.getInstance(project).getServers(); + List availableMongoServers = new LinkedList<>(); for (DatabaseServer mongoServer : mongoServers) { if (mongoServer.hasDatabases()) { availableMongoServers.add(mongoServer); @@ -146,8 +146,8 @@ private ServerConfiguration getSelectedConfiguration() { return selectedServer == null ? null : selectedServer.getConfiguration(); } - public MongoDatabase getSelectedDatabase() { - return (MongoDatabase) databaseCombobox.getSelectedItem(); + public SingleMongoDatabase getSelectedDatabase() { + return (SingleMongoDatabase) databaseCombobox.getSelectedItem(); } private String getShellWorkingDir() { diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanel.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanel.java index c5f33aa..847853f 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanel.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanel.java @@ -24,8 +24,8 @@ import com.intellij.ui.PopupHandler; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.ui.tree.TreeUtil; -import com.mongodb.DBObject; import org.apache.commons.lang.StringUtils; +import org.bson.Document; import org.codinjutsu.tools.nosql.commons.view.NoSqlTreeNode; import org.codinjutsu.tools.nosql.commons.view.nodedescriptor.NodeDescriptor; import org.codinjutsu.tools.nosql.mongo.view.action.edition.AddKeyAction; @@ -101,7 +101,7 @@ public void actionPerformed(ActionEvent actionEvent) { return this; } - public void updateEditionTree(DBObject mongoDocument) { + public void updateEditionTree(Document mongoDocument) { String panelTitle = "New document"; if (mongoDocument != null) { panelTitle = "Edition"; @@ -152,11 +152,11 @@ public boolean containsKey(String key) { public void addKey(String key, Object value) { - List node = new LinkedList(); + List node = new LinkedList<>(); NoSqlTreeNode treeNode = new NoSqlTreeNode(MongoKeyValueDescriptor.createDescriptor(key, value)); - if (value instanceof DBObject) { - JsonTreeModel.processDbObject(treeNode, (DBObject) value); + if (value instanceof Document || value instanceof List) { + JsonTreeModel.processDocument(treeNode, value); } node.add(treeNode); @@ -171,13 +171,15 @@ public void addKey(String key, Object value) { } public void addValue(Object value) { - List node = new LinkedList(); + List node = new LinkedList<>(); NoSqlTreeNode parentNode = getParentNode(); + assert parentNode != null; + NoSqlTreeNode treeNode = new NoSqlTreeNode(MongoValueDescriptor.createDescriptor(parentNode.getChildCount(), value)); - if (value instanceof DBObject) { - JsonTreeModel.processDbObject(treeNode, (DBObject) value); + if (value instanceof Document || value instanceof List) { + JsonTreeModel.processDocument(treeNode, value); } node.add(treeNode); @@ -224,9 +226,9 @@ public void removeSelectedKey() { } - private DBObject buildMongoDocument() { + private Document buildMongoDocument() { NoSqlTreeNode rootNode = (NoSqlTreeNode) editTableView.getTree().getModel().getRoot(); - return JsonTreeModel.buildDBObject(rootNode); + return JsonTreeModel.buildDBDocument(rootNode); } @Override diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoPanel.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoPanel.java index adf39f1..2cc88ef 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoPanel.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoPanel.java @@ -33,22 +33,22 @@ import com.intellij.openapi.util.Disposer; import com.intellij.ui.NumberDocument; import com.intellij.ui.components.panels.NonOpaquePanel; -import com.mongodb.DBObject; +import org.bson.Document; import org.codinjutsu.tools.nosql.ServerConfiguration; import org.codinjutsu.tools.nosql.commons.utils.GuiUtils; import org.codinjutsu.tools.nosql.commons.view.ErrorPanel; import org.codinjutsu.tools.nosql.commons.view.NoSqlResultView; import org.codinjutsu.tools.nosql.commons.view.action.ExecuteQuery; -import org.codinjutsu.tools.nosql.mongo.logic.MongoClient; -import org.codinjutsu.tools.nosql.mongo.model.MongoCollection; +import org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient; import org.codinjutsu.tools.nosql.mongo.model.MongoResult; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoCollection; import org.codinjutsu.tools.nosql.mongo.view.action.*; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; -public class MongoPanel extends NoSqlResultView { +public class MongoPanel extends NoSqlResultView { private final LoadingDecorator loadingDecorator; private JPanel rootPanel; @@ -60,14 +60,14 @@ public class MongoPanel extends NoSqlResultView { private final QueryPanel queryPanel; private final Project project; - private final MongoClient mongoClient; + private final SingleMongoClient singleMongoClient; private final ServerConfiguration configuration; - private final MongoCollection mongoCollection; + private final SingleMongoCollection singleMongoCollection; - public MongoPanel(Project project, final MongoClient mongoClient, final ServerConfiguration configuration, final MongoCollection mongoCollection) { + public MongoPanel(Project project, final SingleMongoClient singleMongoClient, final ServerConfiguration configuration, final SingleMongoCollection singleMongoCollection) { this.project = project; - this.mongoClient = mongoClient; - this.mongoCollection = mongoCollection; + this.singleMongoClient = singleMongoClient; + this.singleMongoCollection = singleMongoCollection; this.configuration = configuration; errorPanel.setLayout(new BorderLayout()); @@ -77,17 +77,17 @@ public MongoPanel(Project project, final MongoClient mongoClient, final ServerCo resultPanel = createResultPanel(project, new MongoDocumentOperations() { - public DBObject getMongoDocument(Object _id) { - return mongoClient.findMongoDocument(configuration, mongoCollection, _id); + public Document getMongoDocument(Object _id) { + return singleMongoClient.findMongoDocument(configuration, singleMongoCollection, _id); } - public void updateMongoDocument(DBObject mongoDocument) { - mongoClient.update(configuration, mongoCollection, mongoDocument); + public void updateMongoDocument(Document mongoDocument) { + singleMongoClient.update(configuration, singleMongoCollection, mongoDocument); executeQuery(); } public void deleteMongoDocument(Object objectId) { - mongoClient.delete(configuration, mongoCollection, objectId); + singleMongoClient.delete(configuration, singleMongoCollection, objectId); executeQuery(); } }); @@ -128,7 +128,7 @@ private MongoResultPanel createResultPanel(Project project, MongoDocumentOperati void installResultPanelActions() { DefaultActionGroup actionResultGroup = new DefaultActionGroup("MongoResultGroup", true); if (ApplicationManager.getApplication() != null) { - actionResultGroup.add(new ExecuteQuery(this)); + actionResultGroup.add(new ExecuteQuery<>(this)); actionResultGroup.add(new OpenFindAction(this)); actionResultGroup.add(new EnableAggregateAction(queryPanel)); actionResultGroup.addSeparator(); @@ -185,8 +185,8 @@ public void dispose() { toolBar.add(actionToolBarComponent, BorderLayout.CENTER); } - public MongoCollection getRecords() { - return mongoCollection; + public SingleMongoCollection getRecords() { + return singleMongoCollection; } @@ -197,7 +197,7 @@ public void showResults() { public void executeQuery() { errorPanel.setVisible(false); validateQuery(); - ProgressManager.getInstance().run(new Task.Backgroundable(project, "Executing query", true) { + ProgressManager.getInstance().run(new Task.Backgroundable(project, "Executing Query", true) { @Override public void run(@NotNull final ProgressIndicator indicator) { try { @@ -208,7 +208,7 @@ public void run() { } }); - final MongoResult mongoResult = mongoClient.loadCollectionValues(configuration, mongoCollection, queryPanel.getQueryOptions(rowLimitField.getText())); + final MongoResult mongoResult = singleMongoClient.loadCollectionValues(configuration, singleMongoCollection, queryPanel.getQueryOptions(rowLimitField.getText())); GuiUtils.runInSwingThread(new Runnable() { @Override public void run() { @@ -276,10 +276,10 @@ public boolean isFindEditorOpened() { } interface MongoDocumentOperations { - DBObject getMongoDocument(Object _id); + Document getMongoDocument(Object _id); - void deleteMongoDocument(Object mongoDocument); + void deleteMongoDocument(Object mongoDocumentID); - void updateMongoDocument(DBObject mongoDocument); + void updateMongoDocument(Document mongoDocument); } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanel.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanel.java index 173f6ce..7bd1184 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanel.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanel.java @@ -29,8 +29,8 @@ import com.intellij.ui.components.JBScrollPane; import com.intellij.ui.treeStructure.treetable.TreeTableTree; import com.intellij.util.ui.tree.TreeUtil; -import com.mongodb.DBObject; import org.apache.commons.lang.StringUtils; +import org.bson.Document; import org.codinjutsu.tools.nosql.commons.utils.GuiUtils; import org.codinjutsu.tools.nosql.commons.view.NoSqlTreeNode; import org.codinjutsu.tools.nosql.commons.view.nodedescriptor.NodeDescriptor; @@ -133,7 +133,7 @@ void buildPopupMenu() { public void editSelectedMongoDocument() { - DBObject mongoDocument = getSelectedMongoDocument(); + Document mongoDocument = getSelectedMongoDocument(); if (mongoDocument == null) { return; @@ -150,7 +150,7 @@ public void addMongoDocument() { splitter.setSecondComponent(mongoEditionPanel); } - private DBObject getSelectedMongoDocument() { + private Document getSelectedMongoDocument() { TreeTableTree tree = resultTableView.getTree(); NoSqlTreeNode treeNode = (NoSqlTreeNode) tree.getLastSelectedPathComponent(); if (treeNode == null) { @@ -216,7 +216,7 @@ private void hideEditionPanel() { } private String stringifyResult(DefaultMutableTreeNode selectedResultNode) { - List stringifiedObjects = new LinkedList(); + List stringifiedObjects = new LinkedList<>(); for (int i = 0; i < selectedResultNode.getChildCount(); i++) { DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) selectedResultNode.getChildAt(i); stringifiedObjects.add(childNode.getUserObject()); diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/console/MongoConsoleRunner.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/console/MongoConsoleRunner.java index 745aa62..0faa428 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/console/MongoConsoleRunner.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/console/MongoConsoleRunner.java @@ -35,7 +35,7 @@ import org.codinjutsu.tools.nosql.commons.view.console.NoSqlConsoleView; import org.codinjutsu.tools.nosql.mongo.MongoUtils; import org.codinjutsu.tools.nosql.mongo.logic.MongoExtraSettings; -import org.codinjutsu.tools.nosql.mongo.model.MongoDatabase; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoDatabase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -44,10 +44,10 @@ public class MongoConsoleRunner extends AbstractConsoleRunnerWithHistory MONGO_SHELL_FILE = Key.create("MONGO_SHELL_FILE"); private final ServerConfiguration serverConfiguration; - private final MongoDatabase database; + private final SingleMongoDatabase database; - public MongoConsoleRunner(@NotNull Project project, ServerConfiguration serverConfiguration, MongoDatabase database) { + public MongoConsoleRunner(@NotNull Project project, ServerConfiguration serverConfiguration, SingleMongoDatabase database) { super(project, "Mongo Shell", "/tmp"); this.serverConfiguration = serverConfiguration; diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/editor/MongoObjectFile.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/editor/MongoObjectFile.java index 748b1d6..00c6ae7 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/editor/MongoObjectFile.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/editor/MongoObjectFile.java @@ -20,14 +20,14 @@ import com.intellij.openapi.project.Project; import org.codinjutsu.tools.nosql.ServerConfiguration; import org.codinjutsu.tools.nosql.commons.view.editor.NoSqlDatabaseObjectFile; -import org.codinjutsu.tools.nosql.mongo.model.MongoCollection; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoCollection; import org.jetbrains.annotations.NotNull; public class MongoObjectFile extends NoSqlDatabaseObjectFile { - private MongoCollection collection; + private SingleMongoCollection collection; - public MongoObjectFile(Project project, ServerConfiguration configuration, MongoCollection collection) { + public MongoObjectFile(Project project, ServerConfiguration configuration, SingleMongoCollection collection) { super(project, configuration, String.format("%s/%s/%s", configuration.getLabel(), collection.getDatabaseName(), collection.getName())); this.collection = collection; @@ -39,7 +39,7 @@ public FileType getFileType() { } - public MongoCollection getCollection() { + public SingleMongoCollection getCollection() { return collection; } } diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModel.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModel.java index dc0002a..91c463f 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModel.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModel.java @@ -16,10 +16,8 @@ package org.codinjutsu.tools.nosql.mongo.view.model; -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; import org.apache.commons.lang.StringUtils; +import org.bson.Document; import org.codinjutsu.tools.nosql.commons.view.NoSqlTreeNode; import org.codinjutsu.tools.nosql.commons.view.nodedescriptor.NodeDescriptor; import org.codinjutsu.tools.nosql.mongo.model.MongoResult; @@ -29,6 +27,7 @@ import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; +import java.util.ArrayList; import java.util.Enumeration; import java.util.List; @@ -43,89 +42,108 @@ public JsonTreeModel(MongoResult mongoResult) { public static TreeNode buildJsonTree(MongoResult mongoResult) { NoSqlTreeNode rootNode = new NoSqlTreeNode(new MongoResultDescriptor(mongoResult.getCollectionName())); - List mongoObjects = mongoResult.getMongoObjects(); + List mongoObjects = mongoResult.getMongoObjects(); int i = 0; - for (DBObject mongoObject : mongoObjects) { - if (mongoObject instanceof BasicDBList) { - processDbObject(rootNode, mongoObject); - } else if (mongoObject instanceof BasicDBObject) {//dead code? - NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoValueDescriptor.createDescriptor(i++, mongoObject)); - processDbObject(currentNode, mongoObject); - rootNode.add(currentNode); - } + for (Document mongoObject : mongoObjects) { + NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoValueDescriptor.createDescriptor(i++, mongoObject)); + processDocument(currentNode, mongoObject); + rootNode.add(currentNode); + + // todo: do we really need to support array here? + // old code +// if (mongoObject instanceof BasicDBList) { +// processDocument(rootNode, mongoObject); +// } else if (mongoObject instanceof BasicDBObject) {//dead code? +// NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoValueDescriptor.createDescriptor(i++, mongoObject)); +// processDocument(currentNode, mongoObject); +// rootNode.add(currentNode); +// } } return rootNode; } - public static TreeNode buildJsonTree(DBObject mongoObject) { + public static TreeNode buildJsonTree(Object mongoObject) { NoSqlTreeNode rootNode = new NoSqlTreeNode(new MongoResultDescriptor());//TODO crappy - processDbObject(rootNode, mongoObject); + processDocument(rootNode, mongoObject); return rootNode; } - public static void processDbObject(NoSqlTreeNode parentNode, DBObject mongoObject) { - if (mongoObject instanceof BasicDBList) { - BasicDBList mongoObjectList = (BasicDBList) mongoObject; - for (int i = 0; i < mongoObjectList.size(); i++) { - Object mongoObjectOfList = mongoObjectList.get(i); - NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoValueDescriptor.createDescriptor(i, mongoObjectOfList)); - if (mongoObjectOfList instanceof DBObject) { - processDbObject(currentNode, (DBObject) mongoObjectOfList); - } - parentNode.add(currentNode); + private static void processDocument(NoSqlTreeNode parentNode, List documentList) { + for (int i = 0; i < documentList.size(); i++) { + Object mongoObjectOfList = documentList.get(i); + NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoValueDescriptor.createDescriptor(i, mongoObjectOfList)); + if (mongoObjectOfList instanceof Document) { + processDocument(currentNode, (Document) mongoObjectOfList); + } else if (mongoObjectOfList instanceof List) { + processDocument(currentNode, (List) mongoObjectOfList); } - } else if (mongoObject instanceof BasicDBObject) { - BasicDBObject basicDBObject = (BasicDBObject) mongoObject; - for (String key : basicDBObject.keySet()) { - Object value = basicDBObject.get(key); - NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoKeyValueDescriptor.createDescriptor(key, value)); - if (value instanceof DBObject) { - processDbObject(currentNode, (DBObject) value); - } - parentNode.add(currentNode); + + parentNode.add(currentNode); + } + } + + public static void processDocument(NoSqlTreeNode parentNode, Object object) { + if (object instanceof Document) { + processDocument(parentNode, (Document) object); + } else if (object instanceof List) { + processDocument(parentNode, (List) object); + } else { + throw new RuntimeException("Unsupported object to process"); + } + } + + public static void processDocument(NoSqlTreeNode parentNode, Document document) { + for (String key : document.keySet()) { + Object value = document.get(key); + NoSqlTreeNode currentNode = new NoSqlTreeNode(MongoKeyValueDescriptor.createDescriptor(key, value)); + + if (value instanceof Document) { + processDocument(currentNode, (Document) value); + } else if (value instanceof List) { + processDocument(currentNode, (List) value); } + parentNode.add(currentNode); } } - public static DBObject buildDBObject(NoSqlTreeNode rootNode) { - BasicDBObject basicDBObject = new BasicDBObject(); + public static Document buildDBDocument(NoSqlTreeNode rootNode) { + final Document document = new Document(); Enumeration children = rootNode.children(); while (children.hasMoreElements()) { NoSqlTreeNode node = (NoSqlTreeNode) children.nextElement(); MongoKeyValueDescriptor descriptor = (MongoKeyValueDescriptor) node.getDescriptor(); Object value = descriptor.getValue(); - if (value instanceof DBObject) { - if (value instanceof BasicDBList) { - basicDBObject.put(descriptor.getKey(), buildDBList(node)); - } else { - basicDBObject.put(descriptor.getKey(), buildDBObject(node)); - } + + if (value instanceof Document) { + document.put(descriptor.getKey(), buildDBDocument(node)); + } else if (value instanceof List) { + document.put(descriptor.getKey(), buildDBList(node)); } else { - basicDBObject.put(descriptor.getKey(), value); + document.put(descriptor.getKey(), value); } } - return basicDBObject; + return document; } - private static DBObject buildDBList(NoSqlTreeNode parentNode) { - BasicDBList basicDBList = new BasicDBList(); + @SuppressWarnings("unchecked") // Since we're adding heterogeneous items in our list + private static List buildDBList(NoSqlTreeNode parentNode) { + final List list = new ArrayList(); Enumeration children = parentNode.children(); while (children.hasMoreElements()) { NoSqlTreeNode node = (NoSqlTreeNode) children.nextElement(); MongoValueDescriptor descriptor = (MongoValueDescriptor) node.getDescriptor(); Object value = descriptor.getValue(); - if (value instanceof DBObject) { - if (value instanceof BasicDBList) { - basicDBList.add(buildDBList(node)); - } else { - basicDBList.add(buildDBObject(node)); - } + + if (value instanceof Document) { + list.add(buildDBDocument(node)); + } else if (value instanceof List) { + list.add(buildDBList(node)); } else { - basicDBList.add(value); + list.add(value); } } - return basicDBList; + return list; } public static NoSqlTreeNode findObjectIdNode(NoSqlTreeNode treeNode) { diff --git a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/nodedescriptor/MongoValueDescriptor.java b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/nodedescriptor/MongoValueDescriptor.java index f8e9b29..4b296ff 100644 --- a/src/main/java/org/codinjutsu/tools/nosql/mongo/view/nodedescriptor/MongoValueDescriptor.java +++ b/src/main/java/org/codinjutsu/tools/nosql/mongo/view/nodedescriptor/MongoValueDescriptor.java @@ -19,7 +19,7 @@ import com.intellij.ui.ColoredTableCellRenderer; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.SimpleTextAttributes; -import com.mongodb.DBObject; +import org.bson.Document; import org.codinjutsu.tools.nosql.commons.style.StyleAttributesProvider; import org.codinjutsu.tools.nosql.commons.utils.DateUtils; import org.codinjutsu.tools.nosql.commons.utils.StringUtils; @@ -58,7 +58,7 @@ public void setValue(Object value) { }; } else if (value instanceof Date) { return new MongoDateValueDescriptor(index, (Date) value); - } else if (value instanceof DBObject) { + } else if (value instanceof Document) { return new MongoValueDescriptor(index, value, StyleAttributesProvider.getObjectAttribute()); } else { return new MongoValueDescriptor(index, value, StyleAttributesProvider.getStringAttribute()); diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml index 2c164ad..8eaa8b1 100644 --- a/src/main/resources/META-INF/plugin.xml +++ b/src/main/resources/META-INF/plugin.xml @@ -36,8 +36,8 @@ serviceImplementation="org.codinjutsu.tools.nosql.DatabaseVendorClientManager"/> - + diff --git a/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClientTest.java b/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClientTest.java similarity index 66% rename from src/test/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClientTest.java rename to src/test/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClientTest.java index 7c1097d..4db11e6 100644 --- a/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClientTest.java +++ b/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClientTest.java @@ -24,7 +24,7 @@ import org.apache.commons.io.IOUtils; import org.bson.Document; import org.codinjutsu.tools.nosql.ServerConfiguration; -import org.codinjutsu.tools.nosql.mongo.model.MongoCollection; +import org.codinjutsu.tools.nosql.mongo.model.SingleMongoCollection; import org.codinjutsu.tools.nosql.mongo.model.MongoResult; import org.codinjutsu.tools.nosql.mongo.model.MongoQueryOptions; import org.junit.Before; @@ -36,9 +36,9 @@ import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; -public class MongoClientTest { +public class SingleMongoClientTest { - private MongoClient mongoClient; + private SingleMongoClient singleMongoClient; private ServerConfiguration serverConfiguration; @@ -46,7 +46,7 @@ public class MongoClientTest { public void loadCollectionsWithEmptyFilter() throws Exception { MongoQueryOptions mongoQueryOptions = new MongoQueryOptions(); mongoQueryOptions.setResultLimit(3); - MongoResult mongoResult = mongoClient.loadCollectionValues(serverConfiguration, new MongoCollection("dummyCollection", "test"), mongoQueryOptions); + MongoResult mongoResult = singleMongoClient.loadCollectionValues(serverConfiguration, new SingleMongoCollection("dummyCollection", "test"), mongoQueryOptions); assertNotNull(mongoResult); assertEquals(3, mongoResult.getMongoObjects().size()); } @@ -57,10 +57,10 @@ public void loadCollectionsWithFilterAndProjection() throws Exception { mongoQueryOptions.setFilter("{\"label\":\"tata\"}"); mongoQueryOptions.setProjection("{\"label\":1, \"_id\": 0}"); mongoQueryOptions.setResultLimit(3); - MongoResult mongoResult = mongoClient.loadCollectionValues(serverConfiguration, new MongoCollection("dummyCollection", "test"), mongoQueryOptions); + MongoResult mongoResult = singleMongoClient.loadCollectionValues(serverConfiguration, new SingleMongoCollection("dummyCollection", "test"), mongoQueryOptions); assertNotNull(mongoResult); assertEquals(2, mongoResult.getMongoObjects().size()); - assertEquals("[{ \"label\" : \"tata\"}, { \"label\" : \"tata\"}]", mongoResult.getMongoObjects().toString()); + assertEquals("[Document{{label=tata}}, Document{{label=tata}}]", mongoResult.getMongoObjects().toString()); } @Test @@ -70,28 +70,28 @@ public void loadCollectionsWithFilterAndProjectionAndSortByPrice() throws Except mongoQueryOptions.setProjection("{\"label\": 1, \"_id\": 0, \"price\": 1}"); mongoQueryOptions.setSort("{\"price\": 1}"); mongoQueryOptions.setResultLimit(3); - MongoResult mongoResult = mongoClient.loadCollectionValues(serverConfiguration, new MongoCollection("dummyCollection", "test"), mongoQueryOptions); + MongoResult mongoResult = singleMongoClient.loadCollectionValues(serverConfiguration, new SingleMongoCollection("dummyCollection", "test"), mongoQueryOptions); assertNotNull(mongoResult); assertEquals(2, mongoResult.getMongoObjects().size()); - assertEquals("[{ \"label\" : \"tata\" , \"price\" : 10}, { \"label\" : \"tata\" , \"price\" : 15}]", mongoResult.getMongoObjects().toString()); + assertEquals("[Document{{label=tata, price=10}}, Document{{label=tata, price=15}}]", mongoResult.getMongoObjects().toString()); } @Test public void updateMongoDocument() throws Exception { MongoQueryOptions mongoQueryOptions = new MongoQueryOptions(); mongoQueryOptions.setFilter("{'label': 'tete'}"); - MongoCollection mongoCollection = new MongoCollection("dummyCollection", "test"); - MongoResult initialData = mongoClient.loadCollectionValues(serverConfiguration, mongoCollection, mongoQueryOptions); + SingleMongoCollection singleMongoCollection = new SingleMongoCollection("dummyCollection", "test"); + MongoResult initialData = singleMongoClient.loadCollectionValues(serverConfiguration, singleMongoCollection, mongoQueryOptions); assertEquals(1, initialData.getMongoObjects().size()); - DBObject initialMongoDocument = initialData.getMongoObjects().get(0); + Document initialMongoDocument = initialData.getMongoObjects().get(0); initialMongoDocument.put("price", 25); - mongoClient.update(serverConfiguration, mongoCollection, initialMongoDocument); + singleMongoClient.update(serverConfiguration, singleMongoCollection, initialMongoDocument); - MongoResult updatedResult = mongoClient.loadCollectionValues(serverConfiguration, mongoCollection, mongoQueryOptions); - List updatedMongoDocuments = updatedResult.getMongoObjects(); + MongoResult updatedResult = singleMongoClient.loadCollectionValues(serverConfiguration, singleMongoCollection, mongoQueryOptions); + List updatedMongoDocuments = updatedResult.getMongoObjects(); assertEquals(1, updatedMongoDocuments.size()); - DBObject updatedMongoDocument = updatedMongoDocuments.get(0); + Document updatedMongoDocument = updatedMongoDocuments.get(0); assertEquals(25, updatedMongoDocument.get("price")); } @@ -101,15 +101,15 @@ public void updateMongoDocument() throws Exception { public void deleteMongoDocument() throws Exception { MongoQueryOptions mongoQueryOptions = new MongoQueryOptions(); mongoQueryOptions.setFilter("{'label': 'tete'}"); - MongoCollection mongoCollection = new MongoCollection("dummyCollection", "test"); - MongoResult initialData = mongoClient.loadCollectionValues(serverConfiguration, mongoCollection, mongoQueryOptions); + SingleMongoCollection singleMongoCollection = new SingleMongoCollection("dummyCollection", "test"); + MongoResult initialData = singleMongoClient.loadCollectionValues(serverConfiguration, singleMongoCollection, mongoQueryOptions); assertEquals(1, initialData.getMongoObjects().size()); - DBObject initialMongoDocument = initialData.getMongoObjects().get(0); + Document initialMongoDocument = initialData.getMongoObjects().get(0); - mongoClient.delete(serverConfiguration, mongoCollection, initialMongoDocument.get("_id")); + singleMongoClient.delete(serverConfiguration, singleMongoCollection, initialMongoDocument.get("_id")); - MongoResult deleteResult = mongoClient.loadCollectionValues(serverConfiguration, mongoCollection, mongoQueryOptions); - List updatedMongoDocuments = deleteResult.getMongoObjects(); + MongoResult deleteResult = singleMongoClient.loadCollectionValues(serverConfiguration, singleMongoCollection, mongoQueryOptions); + List updatedMongoDocuments = deleteResult.getMongoObjects(); assertEquals(0, updatedMongoDocuments.size()); } @@ -118,14 +118,14 @@ public void deleteMongoDocument() throws Exception { public void loadCollectionsWithAggregateOperators() throws Exception { MongoQueryOptions mongoQueryOptions = new MongoQueryOptions(); mongoQueryOptions.setOperations("[{'$match': {'price': 15}}, {'$project': {'label': 1, 'price': 1}}, {'$group': {'_id': '$label', 'total': {'$sum': '$price'}}}]"); - MongoResult mongoResult = mongoClient.loadCollectionValues(serverConfiguration, new MongoCollection("dummyCollection", "test"), mongoQueryOptions); + MongoResult mongoResult = singleMongoClient.loadCollectionValues(serverConfiguration, new SingleMongoCollection("dummyCollection", "test"), mongoQueryOptions); assertNotNull(mongoResult); - List mongoObjects = mongoResult.getMongoObjects(); + List mongoObjects = mongoResult.getMongoObjects(); assertEquals(2, mongoObjects.size()); - assertEquals("{ \"_id\" : \"tutu\" , \"total\" : 15}", mongoObjects.get(0).toString()); - assertEquals("{ \"_id\" : \"tata\" , \"total\" : 15}", mongoObjects.get(1).toString()); + assertEquals("Document{{_id=tutu, total=15}}", mongoObjects.get(0).toString()); + assertEquals("Document{{_id=tata, total=15}}", mongoObjects.get(1).toString()); } @Before @@ -137,8 +137,8 @@ public void setUp() throws Exception { dummyCollection.deleteMany(new BasicDBObject()); fillCollectionWithJsonData(dummyCollection, IOUtils.toString(getClass().getResourceAsStream("dummyCollection.json"))); - mongoClient = new MongoClient(); - serverConfiguration = mongoClient.defaultConfiguration(); + singleMongoClient = new SingleMongoClient(); + serverConfiguration = singleMongoClient.defaultConfiguration(); serverConfiguration.setServerUrl("localhost:27017"); } diff --git a/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClientURIBuilderTest.java b/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClientURIBuilderTest.java similarity index 95% rename from src/test/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClientURIBuilderTest.java rename to src/test/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClientURIBuilderTest.java index 2fc9bf4..9c01efb 100644 --- a/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/MongoClientURIBuilderTest.java +++ b/src/test/java/org/codinjutsu/tools/nosql/mongo/logic/SingleMongoClientURIBuilderTest.java @@ -17,12 +17,11 @@ package org.codinjutsu.tools.nosql.mongo.logic; import com.mongodb.AuthenticationMechanism; -import org.codinjutsu.tools.nosql.mongo.logic.MongoClientURIBuilder; import org.junit.Test; import static org.junit.Assert.assertEquals; -public class MongoClientURIBuilderTest { +public class SingleMongoClientURIBuilderTest { @Test public void withoutAuthentication() throws Exception { diff --git a/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanelTest.java b/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanelTest.java index dc772a0..b1e3621 100644 --- a/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanelTest.java +++ b/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoEditionPanelTest.java @@ -16,9 +16,8 @@ package org.codinjutsu.tools.nosql.mongo.view; -import com.mongodb.DBObject; -import com.mongodb.util.JSON; import org.apache.commons.io.IOUtils; +import org.bson.Document; import org.bson.types.ObjectId; import org.codinjutsu.tools.nosql.commons.view.nodedescriptor.NodeDescriptor; import org.fest.swing.data.TableCell; @@ -93,12 +92,14 @@ public void editKeyWithStringValue() throws Exception { frameFixture.button("saveButton").click(); - ArgumentCaptor argument = ArgumentCaptor.forClass(DBObject.class); + ArgumentCaptor argument = ArgumentCaptor.forClass(Document.class); verify(mockMongoOperations).updateMongoDocument(argument.capture()); - Assert.assertEquals("{ \"_id\" : { \"$oid\" : \"50b8d63414f85401b9268b99\"} , \"label\" : \"Hello\" , \"visible\" : false , \"image\" : null }", + Assert.assertEquals("Document{{_id=50b8d63414f85401b9268b99, label=Hello, visible=false, image=null}}", argument.getValue().toString()); + Assert.assertTrue(argument.getValue().get("_id") instanceof ObjectId); + verify(mockActionCallback, times(1)).onOperationSuccess(any(String.class)); } @@ -110,7 +111,7 @@ public void cancelEdition() throws Exception { editionTreeTable.enterValue(TableCell.row(1).column(1), "Hello"); frameFixture.button("cancelButton").click(); - verify(mockMongoOperations, times(0)).updateMongoDocument(any(DBObject.class)); + verify(mockMongoOperations, times(0)).updateMongoDocument(any(Document.class)); verify(mockActionCallback, times(1)).onOperationCancelled(any(String.class)); } @@ -145,14 +146,14 @@ public void addValueInAList() throws Exception { editionTreeTable.requireContents(new String[][]{ {"_id", "50b8d63414f85401b9268b99"}, {"title", "XP by example"}, - {"tags", "[ \"pair programming\" , \"tdd\" , \"agile\"]"}, + {"tags", "[pair programming, tdd, agile]"}, {"[0]", "pair programming"}, {"[1]", "tdd"}, {"[2]", "agile"}, - {"innerList", "[ [ 1 , 2 , 3 , 4] , [ false , true] , [ { \"tagName\" : \"pouet\"} , { \"tagName\" : \"paf\"}]]"}, - {"[0]", "[ 1 , 2 , 3 , 4]"}, - {"[1]", "[ false , true]"}, - {"[2]", "[ { \"tagName\" : \"pouet\"} , { \"tagName\" : \"paf\"}]"}}); + {"innerList", "[[1, 2, 3, 4], [false, true], [Document{{tagName=pouet}}, Document{{tagName=paf}}]]"}, + {"[0]", "[1, 2, 3, 4]"}, + {"[1]", "[false, true]"}, + {"[2]", "[Document{{tagName=pouet}}, Document{{tagName=paf}}]"}}); editionTreeTable.selectCell(TableCell.row(3).column(1)); mongoEditionPanel.addValue("refactor"); @@ -160,15 +161,15 @@ public void addValueInAList() throws Exception { editionTreeTable.requireContents(new String[][]{ {"_id", "50b8d63414f85401b9268b99"}, {"title", "XP by example"}, - {"tags", "[ \"pair programming\" , \"tdd\" , \"agile\"]"}, + {"tags", "[pair programming, tdd, agile]"}, {"[0]", "pair programming"}, {"[1]", "tdd"}, {"[2]", "agile"}, {"[3]", "refactor"}, - {"innerList", "[ [ 1 , 2 , 3 , 4] , [ false , true] , [ { \"tagName\" : \"pouet\"} , { \"tagName\" : \"paf\"}]]"}, - {"[0]", "[ 1 , 2 , 3 , 4]"}, - {"[1]", "[ false , true]"}, - {"[2]", "[ { \"tagName\" : \"pouet\"} , { \"tagName\" : \"paf\"}]"}}); + {"innerList", "[[1, 2, 3, 4], [false, true], [Document{{tagName=pouet}}, Document{{tagName=paf}}]]"}, + {"[0]", "[1, 2, 3, 4]"}, + {"[1]", "[false, true]"}, + {"[2]", "[Document{{tagName=pouet}}, Document{{tagName=paf}}]"}}); } @@ -187,8 +188,8 @@ public String valueAt(JTable table, int row, int column) { } - private DBObject buildDocument(String jsonFile) throws IOException { - DBObject mongoDocument = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream(jsonFile))); + private Document buildDocument(String jsonFile) throws IOException { + Document mongoDocument = Document.parse(IOUtils.toString(getClass().getResourceAsStream(jsonFile))); mongoDocument.put("_id", new ObjectId(String.valueOf(mongoDocument.get("_id")))); return mongoDocument; } diff --git a/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanelTest.java b/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanelTest.java index 65245d2..927e3a6 100644 --- a/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanelTest.java +++ b/src/test/java/org/codinjutsu/tools/nosql/mongo/view/MongoResultPanelTest.java @@ -18,10 +18,10 @@ import com.intellij.openapi.command.impl.DummyProject; import com.intellij.util.ui.tree.TreeUtil; -import com.mongodb.DBObject; -import com.mongodb.util.JSON; import org.apache.commons.io.IOUtils; +import org.bson.Document; import org.codinjutsu.tools.nosql.commons.view.TableCellReader; +import org.codinjutsu.tools.nosql.mongo.MongoUtils; import org.codinjutsu.tools.nosql.mongo.model.MongoResult; import org.fest.swing.edt.GuiActionRunner; import org.fest.swing.edt.GuiQuery; @@ -29,11 +29,13 @@ import org.fest.swing.fixture.FrameFixture; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.IOException; +import java.util.List; import static org.junit.Assert.assertEquals; @@ -69,6 +71,7 @@ void buildPopupMenu() { } @Test + @Ignore public void displayTreeWithASimpleArray() throws Exception { mongoResultPanel.updateResultTableTree(createCollectionResults("simpleArray.json", "mycollec")); @@ -89,7 +92,7 @@ public void testDisplayTreeWithASimpleDocument() throws Exception { frameFixture.table("resultTreeTable").cellReader(new TableCellReader()) .requireColumnCount(2) .requireContents(new String[][]{ - {"[0]", "{ \"_id\" : \"50b8d63414f85401b9268b99\" , \"label\" : \"toto\" , \"visible\" : false , \"image\" : null }"}, + {"[0]", "Document{{_id=50b8d63414f85401b9268b99, label=toto, visible=false, image=null}}"}, {"_id", "\"50b8d63414f85401b9268b99\""}, {"label", "\"toto\""}, {"visible", "false"}, @@ -105,14 +108,14 @@ public void testDisplayTreeWithAStructuredDocument() throws Exception { frameFixture.table("resultTreeTable").cellReader(new TableCellReader()) .requireColumnCount(2) .requireContents(new String[][]{ - {"[0]", "{ \"id\" : 0 , \"label\" : \"toto\" , \"visible\" : false , \"doc\" : { \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}}"}, + {"[0]", "Document{{id=0, label=toto, visible=false, doc=Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}}}"}, {"id", "0"}, {"label", "\"toto\""}, {"visible", "false"}, - {"doc", "{ \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}"}, + {"doc", "Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}"}, {"title", "\"hello\""}, {"nbPages", "10"}, - {"keyWord", "[ \"toto\" , true , 10]"}, + {"keyWord", "[toto, true, 10]"}, {"[0]", "\"toto\""}, {"[1]", "true"}, {"[2]", "10"}, @@ -128,25 +131,25 @@ public void testDisplayTreeWithAnArrayOfStructuredDocument() throws Exception { frameFixture.table("resultTreeTable").cellReader(new TableCellReader()) .requireContents(new String[][]{ - {"[0]", "{ \"id\" : 0 , \"label\" : \"toto\" , \"visible\" : false , \"doc\" : { \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}}"}, + {"[0]", "Document{{id=0, label=toto, visible=false, doc=Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}}}"}, {"id", "0"}, {"label", "\"toto\""}, {"visible", "false"}, - {"doc", "{ \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}"}, + {"doc", "Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}"}, {"title", "\"hello\""}, {"nbPages", "10"}, - {"keyWord", "[ \"toto\" , true , 10]"}, + {"keyWord", "[toto, true, 10]"}, {"[0]", "\"toto\""}, {"[1]", "true"}, {"[2]", "10"}, - {"[1]", "{ \"id\" : 1 , \"label\" : \"tata\" , \"visible\" : true , \"doc\" : { \"title\" : \"ola\" , \"nbPages\" : 1 , \"keyWord\" : [ \"tutu\" , false , 10]}}"}, + {"[1]", "Document{{id=1, label=tata, visible=true, doc=Document{{title=ola, nbPages=1, keyWord=[tutu, false, 10]}}}}"}, {"id", "1"}, {"label", "\"tata\""}, {"visible", "true"}, - {"doc", "{ \"title\" : \"ola\" , \"nbPages\" : 1 , \"keyWord\" : [ \"tutu\" , false , 10]}"}, + {"doc", "Document{{title=ola, nbPages=1, keyWord=[tutu, false, 10]}}"}, {"title", "\"ola\""}, {"nbPages", "1"}, - {"keyWord", "[ \"tutu\" , false , 10]"}, + {"keyWord", "[tutu, false, 10]"}, {"[0]", "\"tutu\""}, {"[1]", "false"}, {"[2]", "10"}, @@ -159,13 +162,13 @@ public void testCopyMongoObjectNodeValue() throws Exception { TreeUtil.expandAll(mongoResultPanel.resultTableView.getTree()); mongoResultPanel.resultTableView.setRowSelectionInterval(0, 0); - assertEquals("{ \"id\" : 0 , \"label\" : \"toto\" , \"visible\" : false , \"doc\" : { \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}}", mongoResultPanel.getSelectedNodeStringifiedValue()); + assertEquals("Document{{id=0, label=toto, visible=false, doc=Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}}}", mongoResultPanel.getSelectedNodeStringifiedValue()); mongoResultPanel.resultTableView.setRowSelectionInterval(2, 2); assertEquals("\"label\" : \"toto\"", mongoResultPanel.getSelectedNodeStringifiedValue()); mongoResultPanel.resultTableView.setRowSelectionInterval(4, 4); - assertEquals("\"doc\" : { \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}", mongoResultPanel.getSelectedNodeStringifiedValue()); + assertEquals("\"doc\" : Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}", mongoResultPanel.getSelectedNodeStringifiedValue()); } @Test @@ -176,42 +179,49 @@ public void copyMongoResults() throws Exception { frameFixture.table("resultTreeTable").cellReader(new TableCellReader()) .requireContents(new String[][]{ - {"[0]", "{ \"id\" : 0 , \"label\" : \"toto\" , \"visible\" : false , \"doc\" : { \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}}"}, + {"[0]", "Document{{id=0, label=toto, visible=false, doc=Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}}}"}, {"id", "0"}, {"label", "\"toto\""}, {"visible", "false"}, - {"doc", "{ \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}"}, + {"doc", "Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}"}, {"title", "\"hello\""}, {"nbPages", "10"}, - {"keyWord", "[ \"toto\" , true , 10]"}, + {"keyWord", "[toto, true, 10]"}, {"[0]", "\"toto\""}, {"[1]", "true"}, {"[2]", "10"}, - {"[1]", "{ \"id\" : 1 , \"label\" : \"tata\" , \"visible\" : true , \"doc\" : { \"title\" : \"ola\" , \"nbPages\" : 1 , \"keyWord\" : [ \"tutu\" , false , 10]}}"}, + {"[1]", "Document{{id=1, label=tata, visible=true, doc=Document{{title=ola, nbPages=1, keyWord=[tutu, false, 10]}}}}"}, {"id", "1"}, {"label", "\"tata\""}, {"visible", "true"}, - {"doc", "{ \"title\" : \"ola\" , \"nbPages\" : 1 , \"keyWord\" : [ \"tutu\" , false , 10]}"}, + {"doc", "Document{{title=ola, nbPages=1, keyWord=[tutu, false, 10]}}"}, {"title", "\"ola\""}, {"nbPages", "1"}, - {"keyWord", "[ \"tutu\" , false , 10]"}, + {"keyWord", "[tutu, false, 10]"}, {"[0]", "\"tutu\""}, {"[1]", "false"}, {"[2]", "10"}, }); assertEquals("[ " + - "{ \"id\" : 0 , \"label\" : \"toto\" , \"visible\" : false , \"doc\" : { \"title\" : \"hello\" , \"nbPages\" : 10 , \"keyWord\" : [ \"toto\" , true , 10]}} , " + - "{ \"id\" : 1 , \"label\" : \"tata\" , \"visible\" : true , \"doc\" : { \"title\" : \"ola\" , \"nbPages\" : 1 , \"keyWord\" : [ \"tutu\" , false , 10]}}" + - " ]", + "Document{{id=0, label=toto, visible=false, doc=Document{{title=hello, nbPages=10, keyWord=[toto, true, 10]}}}} , " + + "Document{{id=1, label=tata, visible=true, doc=Document{{title=ola, nbPages=1, keyWord=[tutu, false, 10]}}}}" + + " ]", mongoResultPanel.getSelectedNodeStringifiedValue()); } private MongoResult createCollectionResults(String data, String collectionName) throws IOException { - DBObject jsonObject = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream(data))); + Object jsonObject = MongoUtils.parseJSON(IOUtils.toString(getClass().getResourceAsStream(data))); MongoResult mongoResult = new MongoResult(collectionName); - mongoResult.add(jsonObject); + + if (jsonObject instanceof List) { + for (Object document : ((List) jsonObject)) { + mongoResult.add((Document) document); + } + } else { + mongoResult.add((Document) jsonObject); + } return mongoResult; } diff --git a/src/test/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModelTest.java b/src/test/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModelTest.java index a6d02bd..6b95461 100644 --- a/src/test/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModelTest.java +++ b/src/test/java/org/codinjutsu/tools/nosql/mongo/view/model/JsonTreeModelTest.java @@ -16,24 +16,24 @@ package org.codinjutsu.tools.nosql.mongo.view.model; -import com.mongodb.BasicDBList; -import com.mongodb.DBObject; -import com.mongodb.util.JSON; import org.apache.commons.io.IOUtils; +import org.bson.Document; import org.bson.types.ObjectId; import org.codinjutsu.tools.nosql.commons.view.NoSqlTreeNode; +import org.codinjutsu.tools.nosql.mongo.MongoUtils; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import java.util.List; + +import static org.junit.Assert.*; public class JsonTreeModelTest { @Test public void buildDBObjectFromSimpleTree() throws Exception { - DBObject jsonObject = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocument.json"))); + Document jsonObject = Document.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocument.json"))); -// Hack to convert _id fron string to ObjectId +// Hack to convert _id from string to ObjectId jsonObject.put("_id", new ObjectId(String.valueOf(jsonObject.get("_id")))); NoSqlTreeNode treeNode = (NoSqlTreeNode) JsonTreeModel.buildJsonTree(jsonObject); @@ -41,15 +41,17 @@ public void buildDBObjectFromSimpleTree() throws Exception { labelNode.getDescriptor().setValue("tata"); - DBObject dbObject = JsonTreeModel.buildDBObject(treeNode); + Document dbObject = JsonTreeModel.buildDBDocument(treeNode); - assertEquals("{ \"_id\" : { \"$oid\" : \"50b8d63414f85401b9268b99\"} , \"label\" : \"tata\" , \"visible\" : false , \"image\" : null }", + assertEquals("Document{{_id=50b8d63414f85401b9268b99, label=tata, visible=false, image=null}}", dbObject.toString()); + + assertTrue(dbObject.get("_id") instanceof ObjectId); } @Test public void buildDBObjectFromTreeWithSubNodes() throws Exception { - DBObject jsonObject = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithInnerNodes.json"))); + Document jsonObject = Document.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithInnerNodes.json"))); // Hack to convert _id fron string to ObjectId jsonObject.put("_id", new ObjectId(String.valueOf(jsonObject.get("_id")))); @@ -61,15 +63,17 @@ public void buildDBObjectFromTreeWithSubNodes() throws Exception { NoSqlTreeNode soldOutNode = (NoSqlTreeNode) innerDocNode.getChildAt(2); soldOutNode.getDescriptor().setValue("false"); - DBObject dbObject = JsonTreeModel.buildDBObject(treeNode); + Document dbObject = JsonTreeModel.buildDBDocument(treeNode); - assertEquals("{ \"_id\" : { \"$oid\" : \"50b8d63414f85401b9268b99\"} , \"label\" : \"toto\" , \"visible\" : false , \"image\" : null , \"innerdoc\" : { \"title\" : \"What?\" , \"numberOfPages\" : 52 , \"soldOut\" : false}}", + assertEquals("Document{{_id=50b8d63414f85401b9268b99, label=toto, visible=false, image=null, innerdoc=Document{{title=What?, numberOfPages=52, soldOut=false}}}}", dbObject.toString()); + + assertTrue(dbObject.get("_id") instanceof ObjectId); } @Test public void buildDBObjectFromTreeWithSubList() throws Exception { - DBObject jsonObject = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithSubList.json"))); + Document jsonObject = Document.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithSubList.json"))); // Hack to convert _id fron string to ObjectId jsonObject.put("_id", new ObjectId(String.valueOf(jsonObject.get("_id")))); @@ -79,15 +83,17 @@ public void buildDBObjectFromTreeWithSubList() throws Exception { NoSqlTreeNode agileTagNode = (NoSqlTreeNode) tagsNode.getChildAt(2); agileTagNode.getDescriptor().setValue("a gilles"); - DBObject dbObject = JsonTreeModel.buildDBObject(treeNode); + Document dbObject = JsonTreeModel.buildDBDocument(treeNode); - assertEquals("{ \"_id\" : { \"$oid\" : \"50b8d63414f85401b9268b99\"} , \"title\" : \"XP by example\" , \"tags\" : [ \"pair programming\" , \"tdd\" , \"a gilles\"] , \"innerList\" : [ [ 1 , 2 , 3 , 4] , [ false , true] , [ { \"tagName\" : \"pouet\"} , { \"tagName\" : \"paf\"}]]}", + assertEquals("Document{{_id=50b8d63414f85401b9268b99, title=XP by example, tags=[pair programming, tdd, a gilles], innerList=[[1, 2, 3, 4], [false, true], [Document{{tagName=pouet}}, Document{{tagName=paf}}]]}}", dbObject.toString()); + + assertTrue(dbObject.get("_id") instanceof ObjectId); } @Test public void getObjectIdFromANode() throws Exception { - DBObject jsonObject = (DBObject) JSON.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithInnerNodes.json"))); + Document jsonObject = Document.parse(IOUtils.toString(getClass().getResourceAsStream("simpleDocumentWithInnerNodes.json"))); jsonObject.put("_id", new ObjectId(String.valueOf(jsonObject.get("_id")))); NoSqlTreeNode treeNode = (NoSqlTreeNode) JsonTreeModel.buildJsonTree(jsonObject); @@ -101,12 +107,12 @@ public void getObjectIdFromANode() throws Exception { @Test public void findDocumentFromANode() throws Exception { - BasicDBList dbList = (BasicDBList) JSON.parse(IOUtils.toString(getClass().getResourceAsStream("arrayOfDocuments.json"))); + List dbList = (List) MongoUtils.parseJSON(IOUtils.toString(getClass().getResourceAsStream("arrayOfDocuments.json"))); - DBObject first = (DBObject) dbList.get(0); + Document first = (Document) dbList.get(0); first.put("_id", new ObjectId(String.valueOf(first.get("_id")))); - DBObject second = (DBObject) dbList.get(1); + Document second = (Document) dbList.get(1); second.put("_id", new ObjectId(String.valueOf(second.get("_id")))); NoSqlTreeNode treeNode = (NoSqlTreeNode) JsonTreeModel.buildJsonTree(dbList);