Skip to content
Browse files

Add normalization

  • Loading branch information...
1 parent 9da8ba8 commit 8f09d0ce59183309f511b73e52073710e41adcd7 @leodagdag committed Oct 4, 2012
View
22 .gitattributes
@@ -0,0 +1,22 @@
+# Auto detect text files and perform LF normalization
+* text=auto
+
+# Custom for Visual Studio
+*.cs diff=csharp
+*.sln merge=union
+*.csproj merge=union
+*.vbproj merge=union
+*.fsproj merge=union
+*.dbproj merge=union
+
+# Standard to msysgit
+*.doc diff=astextplain
+*.DOC diff=astextplain
+*.docx diff=astextplain
+*.DOCX diff=astextplain
+*.dot diff=astextplain
+*.DOT diff=astextplain
+*.pdf diff=astextplain
+*.PDF diff=astextplain
+*.rtf diff=astextplain
+*.RTF diff=astextplain
View
122 project/Build.scala
@@ -1,61 +1,61 @@
-import sbt._
-import Keys._
-
-object Play2MorphiaPluginBuild extends Build {
-
- import Resolvers._
- import Dependencies._
- import BuildSettings._
-
- lazy val Play2MorphiaPlugin = Project(
- "play2-morphia-plugin",
- file("."),
- settings = buildSettings ++ Seq(
- libraryDependencies := runtime ++ test,
- publishMavenStyle := true,
- publishTo := Some(githubRepository),
- scalacOptions ++= Seq("-Xlint","-deprecation", "-unchecked","-encoding", "utf8"),
- javacOptions ++= Seq("-encoding", "utf8", "-g"),
- resolvers ++= Seq(DefaultMavenRepository, Resolvers.typesafeRepository, Resolvers.morphiaRepository),
- checksums := Nil // To prevent proxyToys downloding fails https://github.com/leodagdag/play2-morphia-plugin/issues/11
- )
- ).settings()
-
- object Resolvers {
- val githubRepository = Resolver.file("GitHub Repository", Path.userHome / "dev" / "leodagdag.github.com" / "repository" asFile)(Resolver.mavenStylePatterns)
- val dropboxRepository = Resolver.file("Dropbox Repository", Path.userHome / "Dropbox" / "Public" / "repository" asFile)(Resolver.mavenStylePatterns)
- val typesafeRepository = "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
- val morphiaRepository = "Morphia Repository" at "http://morphia.googlecode.com/svn/mavenrepo/"
- }
-
- object Dependencies {
- val runtime = Seq(
- "com.google.code.morphia" % "morphia" % "1.00-SNAPSHOT",
- "com.google.code.morphia" % "morphia-logging-slf4j" % "0.99",
- "com.google.code.morphia" % "morphia-validation" % "0.99",
- "cglib" % "cglib-nodep" % "[2.1_3,)",
- "com.thoughtworks.proxytoys" % "proxytoys" % "1.0",
- "play" %% "play" % "2.0.4" % "compile" notTransitive(),
- ("org.springframework" % "spring-core" % "3.0.7.RELEASE" notTransitive())
- .exclude("org.springframework", "spring-asm")
- .exclude("commons-logging", "commons-logging"),
- ("org.springframework" % "spring-beans" % "3.0.7.RELEASE" notTransitive())
- .exclude("org.springframework", "spring-core")
- )
- val test = Seq(
- "play" %% "play-test" % "2.0.4" % "test"
- )
- }
-
- object BuildSettings {
- val buildOrganization = "leodagdag"
- val buildVersion = "0.0.7"
- val buildScalaVersion = "2.9.1"
- val buildSbtVersion = "0.11.3"
- val buildSettings = Defaults.defaultSettings ++ Seq (
- organization := buildOrganization,
- version := buildVersion,
- scalaVersion := buildScalaVersion
- )
- }
-}
+import sbt._
+import Keys._
+
+object Play2MorphiaPluginBuild extends Build {
+
+ import Resolvers._
+ import Dependencies._
+ import BuildSettings._
+
+ lazy val Play2MorphiaPlugin = Project(
+ "play2-morphia-plugin",
+ file("."),
+ settings = buildSettings ++ Seq(
+ libraryDependencies := runtime ++ test,
+ publishMavenStyle := true,
+ publishTo := Some(githubRepository),
+ scalacOptions ++= Seq("-Xlint","-deprecation", "-unchecked","-encoding", "utf8"),
+ javacOptions ++= Seq("-encoding", "utf8", "-g"),
+ resolvers ++= Seq(DefaultMavenRepository, Resolvers.typesafeRepository, Resolvers.morphiaRepository),
+ checksums := Nil // To prevent proxyToys downloding fails https://github.com/leodagdag/play2-morphia-plugin/issues/11
+ )
+ ).settings()
+
+ object Resolvers {
+ val githubRepository = Resolver.file("GitHub Repository", Path.userHome / "dev" / "leodagdag.github.com" / "repository" asFile)(Resolver.mavenStylePatterns)
+ val dropboxRepository = Resolver.file("Dropbox Repository", Path.userHome / "Dropbox" / "Public" / "repository" asFile)(Resolver.mavenStylePatterns)
+ val typesafeRepository = "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
+ val morphiaRepository = "Morphia Repository" at "http://morphia.googlecode.com/svn/mavenrepo/"
+ }
+
+ object Dependencies {
+ val runtime = Seq(
+ "com.google.code.morphia" % "morphia" % "1.00-SNAPSHOT",
+ "com.google.code.morphia" % "morphia-logging-slf4j" % "0.99",
+ "com.google.code.morphia" % "morphia-validation" % "0.99",
+ "cglib" % "cglib-nodep" % "[2.1_3,)",
+ "com.thoughtworks.proxytoys" % "proxytoys" % "1.0",
+ "play" %% "play" % "2.0.4" % "compile" notTransitive(),
+ ("org.springframework" % "spring-core" % "3.0.7.RELEASE" notTransitive())
+ .exclude("org.springframework", "spring-asm")
+ .exclude("commons-logging", "commons-logging"),
+ ("org.springframework" % "spring-beans" % "3.0.7.RELEASE" notTransitive())
+ .exclude("org.springframework", "spring-core")
+ )
+ val test = Seq(
+ "play" %% "play-test" % "2.0.4" % "test"
+ )
+ }
+
+ object BuildSettings {
+ val buildOrganization = "leodagdag"
+ val buildVersion = "0.0.7"
+ val buildScalaVersion = "2.9.1"
+ val buildSbtVersion = "0.11.3"
+ val buildSettings = Defaults.defaultSettings ++ Seq (
+ organization := buildOrganization,
+ version := buildVersion,
+ scalaVersion := buildScalaVersion
+ )
+ }
+}
View
16 project/plugins.sbt
@@ -1,8 +1,8 @@
-logLevel := Level.Warn
-
-// Use for intellij
-resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/"
-
-// Use for intellij
-addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.1.0")
-
+logLevel := Level.Warn
+
+// Use for intellij
+resolvers += "sbt-idea-repo" at "http://mpeltonen.github.com/maven/"
+
+// Use for intellij
+addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.1.0")
+
View
162 src/main/java/leodagdag/play2morphia/Blob.java
@@ -1,81 +1,81 @@
-package leodagdag.play2morphia;
-
-import com.google.code.morphia.annotations.Transient;
-import com.mongodb.BasicDBObject;
-import com.mongodb.DBObject;
-import com.mongodb.gridfs.GridFSDBFile;
-import com.mongodb.gridfs.GridFSInputFile;
-import org.bson.types.ObjectId;
-import play.Logger;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.UUID;
-
-public class Blob {
-
- @Transient
- private GridFSDBFile gridFSDBFile;
-
- public Blob() {
- }
-
- public Blob(InputStream is, String type) {
- this();
- set(is, type);
- }
-
- public Blob(File inputFile, String type) {
- this();
- try {
- set(inputFile, type);
- } catch (IOException e) {
- Logger.error(String.format("File not found: %s (%s)", inputFile.getAbsolutePath(), e.getMessage()));
- }
- }
-
- public Blob(String id) {
- DBObject queryObj = new BasicDBObject("name", id);
- gridFSDBFile = MorphiaPlugin.gridFs().findOne(queryObj);
- }
-
- void set(File file, String type) throws IOException {
- if (!file.exists()) {
- Logger.warn(String.format("File not exists: %s", file));
- return;
- }
- GridFSInputFile inputFile = MorphiaPlugin.gridFs().createFile(file);
- inputFile.setContentType(type);
- inputFile.save();
- this.gridFSDBFile = MorphiaPlugin.gridFs().findOne(new ObjectId(inputFile.getId().toString()));
- }
-
- void set(InputStream is, String type) {
- GridFSInputFile inputFile = MorphiaPlugin.gridFs().createFile(is);
- inputFile.setContentType(type);
- inputFile.put("name", UUID.randomUUID().toString());
- inputFile.save();
- gridFSDBFile = MorphiaPlugin.gridFs().findOne(new ObjectId(inputFile.getId().toString()));
- }
-
- public long length() {
- return gridFSDBFile == null ? 0 : gridFSDBFile.getLength();
- }
-
- public String type() {
- return gridFSDBFile.getContentType();
- }
-
- public boolean exists() {
- return gridFSDBFile != null && gridFSDBFile.getId() != null;
- }
-
- public GridFSDBFile getGridFSFile() {
- return gridFSDBFile;
- }
-
- public static void delete(String name) {
- MorphiaPlugin.gridFs().remove(new BasicDBObject("name", name));
- }
-}
+package leodagdag.play2morphia;
+
+import com.google.code.morphia.annotations.Transient;
+import com.mongodb.BasicDBObject;
+import com.mongodb.DBObject;
+import com.mongodb.gridfs.GridFSDBFile;
+import com.mongodb.gridfs.GridFSInputFile;
+import org.bson.types.ObjectId;
+import play.Logger;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.UUID;
+
+public class Blob {
+
+ @Transient
+ private GridFSDBFile gridFSDBFile;
+
+ public Blob() {
+ }
+
+ public Blob(InputStream is, String type) {
+ this();
+ set(is, type);
+ }
+
+ public Blob(File inputFile, String type) {
+ this();
+ try {
+ set(inputFile, type);
+ } catch (IOException e) {
+ Logger.error(String.format("File not found: %s (%s)", inputFile.getAbsolutePath(), e.getMessage()));
+ }
+ }
+
+ public Blob(String id) {
+ DBObject queryObj = new BasicDBObject("name", id);
+ gridFSDBFile = MorphiaPlugin.gridFs().findOne(queryObj);
+ }
+
+ void set(File file, String type) throws IOException {
+ if (!file.exists()) {
+ Logger.warn(String.format("File not exists: %s", file));
+ return;
+ }
+ GridFSInputFile inputFile = MorphiaPlugin.gridFs().createFile(file);
+ inputFile.setContentType(type);
+ inputFile.save();
+ this.gridFSDBFile = MorphiaPlugin.gridFs().findOne(new ObjectId(inputFile.getId().toString()));
+ }
+
+ void set(InputStream is, String type) {
+ GridFSInputFile inputFile = MorphiaPlugin.gridFs().createFile(is);
+ inputFile.setContentType(type);
+ inputFile.put("name", UUID.randomUUID().toString());
+ inputFile.save();
+ gridFSDBFile = MorphiaPlugin.gridFs().findOne(new ObjectId(inputFile.getId().toString()));
+ }
+
+ public long length() {
+ return gridFSDBFile == null ? 0 : gridFSDBFile.getLength();
+ }
+
+ public String type() {
+ return gridFSDBFile.getContentType();
+ }
+
+ public boolean exists() {
+ return gridFSDBFile != null && gridFSDBFile.getId() != null;
+ }
+
+ public GridFSDBFile getGridFSFile() {
+ return gridFSDBFile;
+ }
+
+ public static void delete(String name) {
+ MorphiaPlugin.gridFs().remove(new BasicDBObject("name", name));
+ }
+}
View
458 src/main/java/leodagdag/play2morphia/Model.java
@@ -1,229 +1,229 @@
-package leodagdag.play2morphia;
-
-import com.google.code.morphia.annotations.Id;
-import com.google.code.morphia.annotations.Transient;
-import com.google.code.morphia.mapping.Mapper;
-import com.google.code.morphia.query.QueryImpl;
-import com.mongodb.gridfs.GridFSDBFile;
-import org.springframework.beans.BeanWrapperImpl;
-import play.Logger;
-
-import java.beans.PropertyDescriptor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import static leodagdag.play2morphia.MorphiaPlugin.ds;
-import static play.libs.F.Tuple;
-
-public class Model {
- private static String fieldName;
-
- // -- Magic to dynamically access the @Id property
-
- @Transient
- private Tuple<Method, Method> _idGetSet;
-
- private Tuple<Method, Method> _idAccessors() {
- if (_idGetSet == null) {
- try {
- Class<?> clazz = this.getClass();
- while (clazz != null) {
- for (Field f : clazz.getDeclaredFields()) {
- if (f.isAnnotationPresent(Id.class)) {
- PropertyDescriptor idProperty = new BeanWrapperImpl(this).getPropertyDescriptor(f.getName());
- _idGetSet = Tuple(idProperty.getReadMethod(), idProperty.getWriteMethod());
- }
- }
- clazz = clazz.getSuperclass();
- }
- if (_idGetSet == null) {
- throw new RuntimeException("No @com.google.code.morphia.annotations.Id field found in class [" + this.getClass() + "]");
- }
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- return _idGetSet;
- }
-
- /**
- * Id getter
- * @return
- */
- private Object _getId() {
- try {
- return _idAccessors()._1.invoke(this);
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Id setter
- * @param id
- */
- private void _setId(Object id) {
- try {
- _idAccessors()._2.invoke(this, id);
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
-
- public void _post_Load() {
- loadBlobs();
- }
-
- /*
- * Search Methods
- */
- public static class Finder<I, T extends Model> extends QueryImpl<T> {
-
- private final Class<I> idType;
- private final Class<T> type;
-
- public Finder(Class<I> idType, Class<T> type) {
- super(type, MorphiaPlugin.ds().getCollection(type), MorphiaPlugin.ds());
- this.idType = idType;
- this.type = type;
- }
-
- public T byId(Object id) {
- return MorphiaPlugin.ds().createQuery(type).field(Mapper.ID_KEY).equal(id).get();
- }
-
- public List<T> all() {
- return MorphiaPlugin.ds().find(type).asList();
- }
- }
-
- /*
- * Life methods
- */
- @SuppressWarnings("unchecked")
- public <T extends Model> T insert() {
- ds().save(this);
- saveBlobs();
- return (T) this;
- }
-
- @SuppressWarnings("unchecked")
- public <T extends Model> T update(Object id) {
- _setId(id);
- ds().save(this);
- saveBlobs();
- return (T) this;
- }
-
- @SuppressWarnings("unchecked")
- public <T extends Model> T update() {
- ds().save(this);
- saveBlobs();
- return (T) this;
- }
-
- public void delete() {
- deleteBlobs();
- ds().delete(this);
- }
-
- @SuppressWarnings("unchecked")
- public <T extends Model> T refresh() {
- return (T) ds().get(this);
- }
-
- /*
- * Blobs management
- */
- private void saveBlobs() {
- try {
- List<Field> blobFields = new ArrayList<Field>();
- Field[] fields = this.getClass().getFields();
- for (Field field : fields) {
- if (field.getType().equals(Blob.class)) {
- blobFields.add(field);
- }
- }
- if (blobFields.isEmpty()) {
- return;
- }
- for (Field blobField : blobFields) {
- Blob blob = (Blob) blobField.get(this);
- String bloblFieldName = computeBlobFileName(blobField.getName());
- Blob.delete(bloblFieldName); // <= ... we delete it from database
- if (null != blob) { // <= If blob is not null
- GridFSDBFile gridFSFile = blob.getGridFSFile();
- if (null != gridFSFile) {
- gridFSFile.put("name", bloblFieldName);
- gridFSFile.save();
- }
- }
- }
- } catch (Exception e) {
- Logger.error("Error during save blob", e);
- }
- }
-
- private void deleteBlobs() {
- try {
- List<Field> blobFields = new ArrayList<Field>();
- Field[] fields = this.getClass().getFields();
- for (Field field : fields) {
- if (field.getClass().equals(Blob.class)) {
- blobFields.add(field);
- }
- }
- if (blobFields.isEmpty()) {
- return;
- }
- for (Field blobField : blobFields) {
- String bloblFieldName = computeBlobFileName(blobField.getName());
- Blob.delete(bloblFieldName); // <= ... we delete it ONLY from
- // Database
- }
- } catch (Exception e) {
- Logger.error("Error during save blob", e);
- }
- }
-
- protected void loadBlobs() {
- try {
- Class<?> clazz = this.getClass();
- List<Field> blobFields = new ArrayList<Field>();
- while (clazz != null) {
- for (Field f : clazz.getDeclaredFields()) {
- if (f.getType().equals(Blob.class)) {
- blobFields.add(f);
- }
- }
- clazz = clazz.getSuperclass();
- }
- if (!blobFields.isEmpty()) {
- for (Field blobField : blobFields) {
- String fileName = computeBlobFileName(blobField.getName());
- Blob b = new Blob(fileName);
- if (b.exists()) {
- blobField.set(this, b);
- }
- }
- }
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- protected String computeBlobFileName(String fieldName) {
- return String.format("%s_%s_%s", getClass().getSimpleName(), _getId(), fieldName);
- }
-}
+package leodagdag.play2morphia;
+
+import com.google.code.morphia.annotations.Id;
+import com.google.code.morphia.annotations.Transient;
+import com.google.code.morphia.mapping.Mapper;
+import com.google.code.morphia.query.QueryImpl;
+import com.mongodb.gridfs.GridFSDBFile;
+import org.springframework.beans.BeanWrapperImpl;
+import play.Logger;
+
+import java.beans.PropertyDescriptor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import static leodagdag.play2morphia.MorphiaPlugin.ds;
+import static play.libs.F.Tuple;
+
+public class Model {
+ private static String fieldName;
+
+ // -- Magic to dynamically access the @Id property
+
+ @Transient
+ private Tuple<Method, Method> _idGetSet;
+
+ private Tuple<Method, Method> _idAccessors() {
+ if (_idGetSet == null) {
+ try {
+ Class<?> clazz = this.getClass();
+ while (clazz != null) {
+ for (Field f : clazz.getDeclaredFields()) {
+ if (f.isAnnotationPresent(Id.class)) {
+ PropertyDescriptor idProperty = new BeanWrapperImpl(this).getPropertyDescriptor(f.getName());
+ _idGetSet = Tuple(idProperty.getReadMethod(), idProperty.getWriteMethod());
+ }
+ }
+ clazz = clazz.getSuperclass();
+ }
+ if (_idGetSet == null) {
+ throw new RuntimeException("No @com.google.code.morphia.annotations.Id field found in class [" + this.getClass() + "]");
+ }
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return _idGetSet;
+ }
+
+ /**
+ * Id getter
+ * @return
+ */
+ private Object _getId() {
+ try {
+ return _idAccessors()._1.invoke(this);
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Id setter
+ * @param id
+ */
+ private void _setId(Object id) {
+ try {
+ _idAccessors()._2.invoke(this, id);
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+
+ public void _post_Load() {
+ loadBlobs();
+ }
+
+ /*
+ * Search Methods
+ */
+ public static class Finder<I, T extends Model> extends QueryImpl<T> {
+
+ private final Class<I> idType;
+ private final Class<T> type;
+
+ public Finder(Class<I> idType, Class<T> type) {
+ super(type, MorphiaPlugin.ds().getCollection(type), MorphiaPlugin.ds());
+ this.idType = idType;
+ this.type = type;
+ }
+
+ public T byId(Object id) {
+ return MorphiaPlugin.ds().createQuery(type).field(Mapper.ID_KEY).equal(id).get();
+ }
+
+ public List<T> all() {
+ return MorphiaPlugin.ds().find(type).asList();
+ }
+ }
+
+ /*
+ * Life methods
+ */
+ @SuppressWarnings("unchecked")
+ public <T extends Model> T insert() {
+ ds().save(this);
+ saveBlobs();
+ return (T) this;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T extends Model> T update(Object id) {
+ _setId(id);
+ ds().save(this);
+ saveBlobs();
+ return (T) this;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T extends Model> T update() {
+ ds().save(this);
+ saveBlobs();
+ return (T) this;
+ }
+
+ public void delete() {
+ deleteBlobs();
+ ds().delete(this);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T extends Model> T refresh() {
+ return (T) ds().get(this);
+ }
+
+ /*
+ * Blobs management
+ */
+ private void saveBlobs() {
+ try {
+ List<Field> blobFields = new ArrayList<Field>();
+ Field[] fields = this.getClass().getFields();
+ for (Field field : fields) {
+ if (field.getType().equals(Blob.class)) {
+ blobFields.add(field);
+ }
+ }
+ if (blobFields.isEmpty()) {
+ return;
+ }
+ for (Field blobField : blobFields) {
+ Blob blob = (Blob) blobField.get(this);
+ String bloblFieldName = computeBlobFileName(blobField.getName());
+ Blob.delete(bloblFieldName); // <= ... we delete it from database
+ if (null != blob) { // <= If blob is not null
+ GridFSDBFile gridFSFile = blob.getGridFSFile();
+ if (null != gridFSFile) {
+ gridFSFile.put("name", bloblFieldName);
+ gridFSFile.save();
+ }
+ }
+ }
+ } catch (Exception e) {
+ Logger.error("Error during save blob", e);
+ }
+ }
+
+ private void deleteBlobs() {
+ try {
+ List<Field> blobFields = new ArrayList<Field>();
+ Field[] fields = this.getClass().getFields();
+ for (Field field : fields) {
+ if (field.getClass().equals(Blob.class)) {
+ blobFields.add(field);
+ }
+ }
+ if (blobFields.isEmpty()) {
+ return;
+ }
+ for (Field blobField : blobFields) {
+ String bloblFieldName = computeBlobFileName(blobField.getName());
+ Blob.delete(bloblFieldName); // <= ... we delete it ONLY from
+ // Database
+ }
+ } catch (Exception e) {
+ Logger.error("Error during save blob", e);
+ }
+ }
+
+ protected void loadBlobs() {
+ try {
+ Class<?> clazz = this.getClass();
+ List<Field> blobFields = new ArrayList<Field>();
+ while (clazz != null) {
+ for (Field f : clazz.getDeclaredFields()) {
+ if (f.getType().equals(Blob.class)) {
+ blobFields.add(f);
+ }
+ }
+ clazz = clazz.getSuperclass();
+ }
+ if (!blobFields.isEmpty()) {
+ for (Field blobField : blobFields) {
+ String fileName = computeBlobFileName(blobField.getName());
+ Blob b = new Blob(fileName);
+ if (b.exists()) {
+ blobField.set(this, b);
+ }
+ }
+ }
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected String computeBlobFileName(String fieldName) {
+ return String.format("%s_%s_%s", getClass().getSimpleName(), _getId(), fieldName);
+ }
+}
View
452 src/main/java/leodagdag/play2morphia/MorphiaPlugin.java
@@ -1,226 +1,226 @@
-package leodagdag.play2morphia;
-
-import com.google.code.morphia.AbstractEntityInterceptor;
-import com.google.code.morphia.Datastore;
-import com.google.code.morphia.Morphia;
-import com.google.code.morphia.logging.MorphiaLoggerFactory;
-import com.google.code.morphia.logging.slf4j.SLF4JLogrImplFactory;
-import com.google.code.morphia.mapping.Mapper;
-import com.google.code.morphia.validation.MorphiaValidation;
-import com.mongodb.*;
-import com.mongodb.gridfs.GridFS;
-import leodagdag.play2morphia.utils.ConfigKey;
-import leodagdag.play2morphia.utils.MorphiaLogger;
-import leodagdag.play2morphia.utils.StringUtils;
-import play.Application;
-import play.Configuration;
-import play.Plugin;
-
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class MorphiaPlugin extends Plugin {
-
- public static final String VERSION = "0.0.7";
-
- private static Mongo mongo = null;
- private static Morphia morphia = null;
- private static Datastore ds = null;
- private final Application application;
- private static GridFS gridfs;
-
- public MorphiaPlugin(Application application) {
- this.application = application;
- }
-
- @Override
- public void onStart() {
- // Register SLF4JLogrImplFactory as Logger
- // @see http://nesbot.com/2011/11/28/play-2-morphia-logging-error
- MorphiaLoggerFactory.reset();
- MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);
-
- try {
- Configuration morphiaConf = Configuration.root().getConfig(ConfigKey.PREFIX);
- if (morphiaConf == null) {
- throw Configuration.root().reportError(ConfigKey.PREFIX, "Missing Morphia configuration", null);
- }
-
- MorphiaLogger.debug(morphiaConf);
-
- String dbName = morphiaConf.getString(ConfigKey.DB_NAME.getKey());
- if (StringUtils.isBlank(dbName)) {
- throw morphiaConf.reportError(ConfigKey.DB_NAME.getKey(), "Missing Morphia configuration", null);
- }
-
- // Connect to MongoDB
- String seeds = morphiaConf.getString(ConfigKey.DB_SEEDS.getKey());
-
- if (StringUtils.isNotBlank(seeds)) {
- mongo = connect(seeds);
- } else {
- mongo = connect(
- morphiaConf.getString(ConfigKey.DB_HOST.getKey()),
- morphiaConf.getString(ConfigKey.DB_PORT.getKey()));
- }
-
- morphia = new Morphia();
- // Configure validator
- MorphiaValidation morphiaValidation = new MorphiaValidation();
- morphiaValidation.applyTo(morphia);
-
- //Check if credentials parameters are present
- String username = morphiaConf.getString(ConfigKey.DB_USERNAME.getKey());
- String password = morphiaConf.getString(ConfigKey.DB_PASSWORD.getKey());
-
- if (StringUtils.isNotBlank(username) ^ StringUtils.isNotBlank(password)) {
- throw morphiaConf.reportError(ConfigKey.DB_NAME.getKey(), "Missing username or password", null);
- }
-
- // Create datastore
- if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
- ds = morphia.createDatastore(mongo, dbName, username, password.toCharArray());
- } else {
- ds = morphia.createDatastore(mongo, dbName);
- }
-
-
- MorphiaLogger.debug("Datastore [%s] created", dbName);
- // Create GridFS
- String uploadCollection = morphiaConf.getString(ConfigKey.COLLECTION_UPLOADS.getKey());
- if (StringUtils.isBlank(dbName)) {
- uploadCollection = "uploads";
- MorphiaLogger.warn("Missing Morphia configuration key [%s]. Use default value instead [%s]", ConfigKey.COLLECTION_UPLOADS, "uploads");
- }
- gridfs = new GridFS(ds.getDB(), uploadCollection);
- MorphiaLogger.debug("GridFS created", "");
- MorphiaLogger.debug("Add Interceptor...", "");
- morphia.getMapper().addInterceptor(new AbstractEntityInterceptor() {
-
- @Override
- public void postLoad(final Object ent, final DBObject dbObj, final Mapper mapr) {
- if (ent instanceof Model) {
- Model m = (Model) ent;
- m._post_Load();
- }
- }
- });
- MorphiaLogger.debug("Classes mapping...", "");
- mapClasses();
- MorphiaLogger.debug("End of initializing Morphia", "");
- } catch (MongoException e) {
- MorphiaLogger.error(e, "Problem connecting MongoDB");
- throw new RuntimeException(e);
- } catch (ClassNotFoundException e) {
- MorphiaLogger.error(e, "Problem mapping class");
- throw new RuntimeException(e);
- }
- }
-
- private void mapClasses() throws ClassNotFoundException {
- // Register all models.Class
- Set<String> classes = new HashSet<String>();
- classes.addAll(application.getTypesAnnotatedWith("models", com.google.code.morphia.annotations.Entity.class));
- classes.addAll(application.getTypesAnnotatedWith("models", com.google.code.morphia.annotations.Embedded.class));
- for (String clazz : classes) {
- MorphiaLogger.debug("mapping class: %1$s", clazz);
- morphia.map(Class.forName(clazz, true, application.classloader()));
- }
- ds.ensureCaps();
- ds.ensureIndexes();
- }
-
- private final static ConcurrentMap<String, Datastore> dataStores = new ConcurrentHashMap<String, Datastore>();
-
- public static Datastore ds(String dbName) {
- if (StringUtils.isBlank(dbName)) {
- return ds();
- }
- Datastore ds = dataStores.get(dbName);
- if (null == ds) {
- Datastore ds0 = morphia.createDatastore(mongo, dbName);
- ds = dataStores.putIfAbsent(dbName, ds0);
- if (null == ds) {
- ds = ds0;
- }
- }
- return ds;
- }
-
- public static Datastore ds() {
- return ds;
- }
-
- public static GridFS gridFs() {
- return gridfs;
- }
-
- public static DB db() {
- return ds().getDB();
- }
-
- private Mongo connect(String seeds) {
- String[] sa = seeds.split("[;,\\s]+");
- List<ServerAddress> addrs = new ArrayList<ServerAddress>(sa.length);
- for (String s : sa) {
- String[] hp = s.split(":");
- if (0 == hp.length) {
- continue;
- }
- String host = hp[0];
- int port = 27017;
- if (hp.length > 1) {
- port = Integer.parseInt(hp[1]);
- }
- try {
- addrs.add(new ServerAddress(host, port));
- } catch (UnknownHostException e) {
- MorphiaLogger.error(e, "Error creating mongo connection to %s:%s", host, port);
- }
- }
- if (addrs.isEmpty()) {
- throw Configuration.root().reportError(ConfigKey.DB_SEEDS.getKey(), "Cannot connect to mongodb: no replica can be connected", null);
- }
- return new Mongo(addrs);
- }
-
- private Mongo connect(String host, String port) {
- String[] ha = host.split("[,\\s;]+");
- String[] pa = port.split("[,\\s;]+");
- int len = ha.length;
- if (len != pa.length) {
- throw Configuration.root().reportError(ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(), "host and ports number does not match", null);
- }
- if (1 == len) {
- try {
- return new Mongo(ha[0], Integer.parseInt(pa[0]));
- } catch (Exception e) {
- throw Configuration.root().reportError(
- ConfigKey.DB_HOST.getKey() + "-"
- + ConfigKey.DB_PORT.getKey(),
- String.format("Cannot connect to mongodb at %s:%s",
- host, port), e);
- }
- }
- List<ServerAddress> addrs = new ArrayList<ServerAddress>(ha.length);
- for (int i = 0; i < len; ++i) {
- try {
- addrs.add(new ServerAddress(ha[i], Integer.parseInt(pa[i])));
- } catch (Exception e) {
- MorphiaLogger.error(e, "Error creating mongo connection to %s:%s", host, port);
- }
- }
- if (addrs.isEmpty()) {
- throw Configuration.root().reportError(
- ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(), "Cannot connect to mongodb: no replica can be connected",
- null);
- }
- return new Mongo(addrs);
- }
-
-}
+package leodagdag.play2morphia;
+
+import com.google.code.morphia.AbstractEntityInterceptor;
+import com.google.code.morphia.Datastore;
+import com.google.code.morphia.Morphia;
+import com.google.code.morphia.logging.MorphiaLoggerFactory;
+import com.google.code.morphia.logging.slf4j.SLF4JLogrImplFactory;
+import com.google.code.morphia.mapping.Mapper;
+import com.google.code.morphia.validation.MorphiaValidation;
+import com.mongodb.*;
+import com.mongodb.gridfs.GridFS;
+import leodagdag.play2morphia.utils.ConfigKey;
+import leodagdag.play2morphia.utils.MorphiaLogger;
+import leodagdag.play2morphia.utils.StringUtils;
+import play.Application;
+import play.Configuration;
+import play.Plugin;
+
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+public class MorphiaPlugin extends Plugin {
+
+ public static final String VERSION = "0.0.7";
+
+ private static Mongo mongo = null;
+ private static Morphia morphia = null;
+ private static Datastore ds = null;
+ private final Application application;
+ private static GridFS gridfs;
+
+ public MorphiaPlugin(Application application) {
+ this.application = application;
+ }
+
+ @Override
+ public void onStart() {
+ // Register SLF4JLogrImplFactory as Logger
+ // @see http://nesbot.com/2011/11/28/play-2-morphia-logging-error
+ MorphiaLoggerFactory.reset();
+ MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);
+
+ try {
+ Configuration morphiaConf = Configuration.root().getConfig(ConfigKey.PREFIX);
+ if (morphiaConf == null) {
+ throw Configuration.root().reportError(ConfigKey.PREFIX, "Missing Morphia configuration", null);
+ }
+
+ MorphiaLogger.debug(morphiaConf);
+
+ String dbName = morphiaConf.getString(ConfigKey.DB_NAME.getKey());
+ if (StringUtils.isBlank(dbName)) {
+ throw morphiaConf.reportError(ConfigKey.DB_NAME.getKey(), "Missing Morphia configuration", null);
+ }
+
+ // Connect to MongoDB
+ String seeds = morphiaConf.getString(ConfigKey.DB_SEEDS.getKey());
+
+ if (StringUtils.isNotBlank(seeds)) {
+ mongo = connect(seeds);
+ } else {
+ mongo = connect(
+ morphiaConf.getString(ConfigKey.DB_HOST.getKey()),
+ morphiaConf.getString(ConfigKey.DB_PORT.getKey()));
+ }
+
+ morphia = new Morphia();
+ // Configure validator
+ MorphiaValidation morphiaValidation = new MorphiaValidation();
+ morphiaValidation.applyTo(morphia);
+
+ //Check if credentials parameters are present
+ String username = morphiaConf.getString(ConfigKey.DB_USERNAME.getKey());
+ String password = morphiaConf.getString(ConfigKey.DB_PASSWORD.getKey());
+
+ if (StringUtils.isNotBlank(username) ^ StringUtils.isNotBlank(password)) {
+ throw morphiaConf.reportError(ConfigKey.DB_NAME.getKey(), "Missing username or password", null);
+ }
+
+ // Create datastore
+ if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
+ ds = morphia.createDatastore(mongo, dbName, username, password.toCharArray());
+ } else {
+ ds = morphia.createDatastore(mongo, dbName);
+ }
+
+
+ MorphiaLogger.debug("Datastore [%s] created", dbName);
+ // Create GridFS
+ String uploadCollection = morphiaConf.getString(ConfigKey.COLLECTION_UPLOADS.getKey());
+ if (StringUtils.isBlank(dbName)) {
+ uploadCollection = "uploads";
+ MorphiaLogger.warn("Missing Morphia configuration key [%s]. Use default value instead [%s]", ConfigKey.COLLECTION_UPLOADS, "uploads");
+ }
+ gridfs = new GridFS(ds.getDB(), uploadCollection);
+ MorphiaLogger.debug("GridFS created", "");
+ MorphiaLogger.debug("Add Interceptor...", "");
+ morphia.getMapper().addInterceptor(new AbstractEntityInterceptor() {
+
+ @Override
+ public void postLoad(final Object ent, final DBObject dbObj, final Mapper mapr) {
+ if (ent instanceof Model) {
+ Model m = (Model) ent;
+ m._post_Load();
+ }
+ }
+ });
+ MorphiaLogger.debug("Classes mapping...", "");
+ mapClasses();
+ MorphiaLogger.debug("End of initializing Morphia", "");
+ } catch (MongoException e) {
+ MorphiaLogger.error(e, "Problem connecting MongoDB");
+ throw new RuntimeException(e);
+ } catch (ClassNotFoundException e) {
+ MorphiaLogger.error(e, "Problem mapping class");
+ throw new RuntimeException(e);
+ }
+ }
+
+ private void mapClasses() throws ClassNotFoundException {
+ // Register all models.Class
+ Set<String> classes = new HashSet<String>();
+ classes.addAll(application.getTypesAnnotatedWith("models", com.google.code.morphia.annotations.Entity.class));
+ classes.addAll(application.getTypesAnnotatedWith("models", com.google.code.morphia.annotations.Embedded.class));
+ for (String clazz : classes) {
+ MorphiaLogger.debug("mapping class: %1$s", clazz);
+ morphia.map(Class.forName(clazz, true, application.classloader()));
+ }
+ ds.ensureCaps();
+ ds.ensureIndexes();
+ }
+
+ private final static ConcurrentMap<String, Datastore> dataStores = new ConcurrentHashMap<String, Datastore>();
+
+ public static Datastore ds(String dbName) {
+ if (StringUtils.isBlank(dbName)) {
+ return ds();
+ }
+ Datastore ds = dataStores.get(dbName);
+ if (null == ds) {
+ Datastore ds0 = morphia.createDatastore(mongo, dbName);
+ ds = dataStores.putIfAbsent(dbName, ds0);
+ if (null == ds) {
+ ds = ds0;
+ }
+ }
+ return ds;
+ }
+
+ public static Datastore ds() {
+ return ds;
+ }
+
+ public static GridFS gridFs() {
+ return gridfs;
+ }
+
+ public static DB db() {
+ return ds().getDB();
+ }
+
+ private Mongo connect(String seeds) {
+ String[] sa = seeds.split("[;,\\s]+");
+ List<ServerAddress> addrs = new ArrayList<ServerAddress>(sa.length);
+ for (String s : sa) {
+ String[] hp = s.split(":");
+ if (0 == hp.length) {
+ continue;
+ }
+ String host = hp[0];
+ int port = 27017;
+ if (hp.length > 1) {
+ port = Integer.parseInt(hp[1]);
+ }
+ try {
+ addrs.add(new ServerAddress(host, port));
+ } catch (UnknownHostException e) {
+ MorphiaLogger.error(e, "Error creating mongo connection to %s:%s", host, port);
+ }
+ }
+ if (addrs.isEmpty()) {
+ throw Configuration.root().reportError(ConfigKey.DB_SEEDS.getKey(), "Cannot connect to mongodb: no replica can be connected", null);
+ }
+ return new Mongo(addrs);
+ }
+
+ private Mongo connect(String host, String port) {
+ String[] ha = host.split("[,\\s;]+");
+ String[] pa = port.split("[,\\s;]+");
+ int len = ha.length;
+ if (len != pa.length) {
+ throw Configuration.root().reportError(ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(), "host and ports number does not match", null);
+ }
+ if (1 == len) {
+ try {
+ return new Mongo(ha[0], Integer.parseInt(pa[0]));
+ } catch (Exception e) {
+ throw Configuration.root().reportError(
+ ConfigKey.DB_HOST.getKey() + "-"
+ + ConfigKey.DB_PORT.getKey(),
+ String.format("Cannot connect to mongodb at %s:%s",
+ host, port), e);
+ }
+ }
+ List<ServerAddress> addrs = new ArrayList<ServerAddress>(ha.length);
+ for (int i = 0; i < len; ++i) {
+ try {
+ addrs.add(new ServerAddress(ha[i], Integer.parseInt(pa[i])));
+ } catch (Exception e) {
+ MorphiaLogger.error(e, "Error creating mongo connection to %s:%s", host, port);
+ }
+ }
+ if (addrs.isEmpty()) {
+ throw Configuration.root().reportError(
+ ConfigKey.DB_HOST.getKey() + "-" + ConfigKey.DB_PORT.getKey(), "Cannot connect to mongodb: no replica can be connected",
+ null);
+ }
+ return new Mongo(addrs);
+ }
+
+}
View
64 src/main/java/leodagdag/play2morphia/utils/StringUtils.java
@@ -1,32 +1,32 @@
-package leodagdag.play2morphia.utils;
-
-/**
- * User: leodagdag
- * Date: 03/10/12
- * Time: 12:54
- */
-public class StringUtils {
- /**
- * Re-implementation of org.apache.commons.lang.StringUtils.isBlank() to remove dependency
- * @param str
- * @return
- */
- public static boolean isBlank(String str) {
- int strLen;
- if (str == null || (strLen = str.length()) == 0) {
- return true;
- }
- for (int i = 0; i < strLen; i++) {
- if ((Character.isWhitespace(str.charAt(i)) == false)) {
- return false;
- }
- }
- return true;
- }
-
- public static boolean isNotBlank(String str){
- return !StringUtils.isBlank(str);
- }
-
-
-}
+package leodagdag.play2morphia.utils;
+
+/**
+ * User: leodagdag
+ * Date: 03/10/12
+ * Time: 12:54
+ */
+public class StringUtils {
+ /**
+ * Re-implementation of org.apache.commons.lang.StringUtils.isBlank() to remove dependency
+ * @param str
+ * @return
+ */
+ public static boolean isBlank(String str) {
+ int strLen;
+ if (str == null || (strLen = str.length()) == 0) {
+ return true;
+ }
+ for (int i = 0; i < strLen; i++) {
+ if ((Character.isWhitespace(str.charAt(i)) == false)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static boolean isNotBlank(String str){
+ return !StringUtils.isBlank(str);
+ }
+
+
+}
View
238 src/test/java/leodagdag/play2morphia/ModelTest.java
@@ -1,119 +1,119 @@
-package leodagdag.play2morphia;
-
-import com.google.code.morphia.query.Query;
-import leodagdag.play2morphia.models.Post;
-import leodagdag.play2morphia.utils.TestConfig;
-import org.bson.types.ObjectId;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.List;
-
-
-import static org.fest.assertions.Assertions.assertThat;
-import static play.test.Helpers.fakeApplication;
-import static play.test.Helpers.running;
-
-public class ModelTest extends AbstractTest{
-
- @Before
- public void setUp(){
- createEmptyCollection(Post.class);
- assertThat(Post.find().asList().size()).isEqualTo(0);
- }
- @Test
- public void testCreate() {
- running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
- @Override
- public void run() {
- Post post = new Post();
- post.title = "fake post";
- post.insert();
- ObjectId id = post.id;
-
- assertThat(Post.find().byId(id).id).isEqualTo(post.id);
- assertThat(Post.find().byId(id).title).isEqualTo(post.title);
- assertThat(Post.find().asList().size()).isEqualTo(1);
- }
- });
- }
-
- @Test
- public void testUpdate() {
- running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
- @Override
- public void run() {
- Post post = new Post();
- post.title = "fake post";
- post.insert();
-
- post.title = "real title";
- post.update();
- assertThat(Post.find().byId(post.id).title).isEqualTo(post.title);
- }
- });
- }
-
- @Test
- public void testDelete() {
- running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
- @Override
- public void run() {
- Post post = new Post();
- post.title = "fake post";
- post.insert();
- assertThat(Post.find().asList().size()).isEqualTo(1);
-
- post.delete();
- assertThat(Post.find().asList().size()).isEqualTo(0);
- }
- });
- }
-
- @Test
- public void testFindWithOr() {
- running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
- @Override
- public void run() {
- Post alpha1= new Post();
- alpha1.title = "post1";
- alpha1.type = "ALPHA";
- alpha1.insert();
-
- Post beta1= new Post();
- beta1.title = "post1";
- beta1.type = "BETA";
- beta1.insert();
-
- Post beta2= new Post();
- beta2.title = "post1";
- beta2.type = "BETA";
- beta2.insert();
-
- Post gamma1= new Post();
- gamma1.title = "post1";
- gamma1.type = "GAMMA";
- gamma1.insert();
-
- Post zeta1= new Post();
- zeta1.title = "post1";
- zeta1.type = "ZETA";
- zeta1.insert();
-
- assertThat(Post.find().asList().size()).isEqualTo(5);
- Query<Post> q = MorphiaPlugin.ds().createQuery(Post.class);
- q.or(
- q.criteria("type").equal("BETA"),
- q.criteria("type").equal("GAMMA")
- );
- assertThat(q.countAll()).isEqualTo(3);
-
-
- List<String> criterias = Arrays.asList("BETA", "GAMMA");
- assertThat(Post.find().field("type").in(criterias).countAll()).isEqualTo(3);
-
- }
- });
- }
-}
+package leodagdag.play2morphia;
+
+import com.google.code.morphia.query.Query;
+import leodagdag.play2morphia.models.Post;
+import leodagdag.play2morphia.utils.TestConfig;
+import org.bson.types.ObjectId;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+
+import static org.fest.assertions.Assertions.assertThat;
+import static play.test.Helpers.fakeApplication;
+import static play.test.Helpers.running;
+
+public class ModelTest extends AbstractTest{
+
+ @Before
+ public void setUp(){
+ createEmptyCollection(Post.class);
+ assertThat(Post.find().asList().size()).isEqualTo(0);
+ }
+ @Test
+ public void testCreate() {
+ running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
+ @Override
+ public void run() {
+ Post post = new Post();
+ post.title = "fake post";
+ post.insert();
+ ObjectId id = post.id;
+
+ assertThat(Post.find().byId(id).id).isEqualTo(post.id);
+ assertThat(Post.find().byId(id).title).isEqualTo(post.title);
+ assertThat(Post.find().asList().size()).isEqualTo(1);
+ }
+ });
+ }
+
+ @Test
+ public void testUpdate() {
+ running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
+ @Override
+ public void run() {
+ Post post = new Post();
+ post.title = "fake post";
+ post.insert();
+
+ post.title = "real title";
+ post.update();
+ assertThat(Post.find().byId(post.id).title).isEqualTo(post.title);
+ }
+ });
+ }
+
+ @Test
+ public void testDelete() {
+ running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
+ @Override
+ public void run() {
+ Post post = new Post();
+ post.title = "fake post";
+ post.insert();
+ assertThat(Post.find().asList().size()).isEqualTo(1);
+
+ post.delete();
+ assertThat(Post.find().asList().size()).isEqualTo(0);
+ }
+ });
+ }
+
+ @Test
+ public void testFindWithOr() {
+ running(fakeApplication(TestConfig.getInstance().config()), new Runnable() {
+ @Override
+ public void run() {
+ Post alpha1= new Post();
+ alpha1.title = "post1";
+ alpha1.type = "ALPHA";
+ alpha1.insert();
+
+ Post beta1= new Post();
+ beta1.title = "post1";
+ beta1.type = "BETA";
+ beta1.insert();
+
+ Post beta2= new Post();
+ beta2.title = "post1";
+ beta2.type = "BETA";
+ beta2.insert();
+
+ Post gamma1= new Post();
+ gamma1.title = "post1";
+ gamma1.type = "GAMMA";
+ gamma1.insert();
+
+ Post zeta1= new Post();
+ zeta1.title = "post1";
+ zeta1.type = "ZETA";
+ zeta1.insert();
+
+ assertThat(Post.find().asList().size()).isEqualTo(5);
+ Query<Post> q = MorphiaPlugin.ds().createQuery(Post.class);
+ q.or(
+ q.criteria("type").equal("BETA"),
+ q.criteria("type").equal("GAMMA")
+ );
+ assertThat(q.countAll()).isEqualTo(3);
+
+
+ List<String> criterias = Arrays.asList("BETA", "GAMMA");
+ assertThat(Post.find().field("type").in(criterias).countAll()).isEqualTo(3);
+
+ }
+ });
+ }
+}
View
52 src/test/java/leodagdag/play2morphia/models/Post.java
@@ -1,26 +1,26 @@
-package leodagdag.play2morphia.models;
-
-import com.google.code.morphia.annotations.Entity;
-import com.google.code.morphia.annotations.Id;
-import leodagdag.play2morphia.Blob;
-import leodagdag.play2morphia.Model;
-import org.bson.types.ObjectId;
-
-@Entity
-public class Post extends Model {
-
- @Id
- public ObjectId id;
-
- public String title;
-
- public String type;
-
- //public Blob picture;
-
- public static Finder<ObjectId, Post> find(){
- return new Finder<ObjectId, Post>(ObjectId.class, Post.class);
- }
-
-
-}
+package leodagdag.play2morphia.models;
+
+import com.google.code.morphia.annotations.Entity;
+import com.google.code.morphia.annotations.Id;
+import leodagdag.play2morphia.Blob;
+import leodagdag.play2morphia.Model;
+import org.bson.types.ObjectId;
+
+@Entity
+public class Post extends Model {
+
+ @Id
+ public ObjectId id;
+
+ public String title;
+
+ public String type;
+
+ //public Blob picture;
+
+ public static Finder<ObjectId, Post> find(){
+ return new Finder<ObjectId, Post>(ObjectId.class, Post.class);
+ }
+
+
+}

0 comments on commit 8f09d0c

Please sign in to comment.
Something went wrong with that request. Please try again.