#if($package) package $package; #end import org.bson.Document; import org.eclipse.ice.dev.annotations.IPersistenceHandler; import org.eclipse.ice.dev.annotations.PersistenceFilters; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; /** * This is an implementation of $interface<$elementInterface> * that satisfies the dependencies of the {@code @Persisted} Annotation and was * auto-generated by the ICE Framework. */ public class $class implements $interface<$elementInterface> { /** * The name of the collection backing this PersistenceHandler. */ private final static String COLLECTION = "$collection"; /** * The collection in which implementations of $elementInterface will be stored. */ private MongoCollection collection; /** * Convert values from Document to $implementation using mapper. */ private ObjectMapper mapper = new ObjectMapper(); public $class(MongoDatabase db) { this.collection = db.getCollection(COLLECTION); } /** * Save the $elementInterface. * @param element * @throws Exception */ @Override public void save($elementInterface element) throws Exception { this.collection.insertOne(Document.parse(element.toJson())); } /** * Find and retrieve all $elementInterface from the collection. * @return an iterable of the retrieved elements. * @throws Exception */ @Override public Iterable<$elementInterface> findAll() throws Exception { return this.collection.find() .map(doc -> mapper.convertValue(doc, ${implementation}.class)); } /** * Clear all $elementInterface from the collection. * @return * @throws Exception */ @Override public long clear() throws Exception { long count = this.collection.countDocuments(); this.collection.drop(); return count; } #foreach($field in $fields) #if(${field.Getter} && ${field.Searchable}) #if(${field.Unique}) /** * Find $elementInterface by ${field.Name}. * @param ${field.VarName} * @return found element or null */ #if(${field.DefaultField}) @Override #end public $elementInterface findBy${field.NameForMethod}(#fieldtype ${field.VarName}) throws Exception { Document doc = this.collection .find(PersistenceFilters.eq("${field.VarName}", ${field.VarName})) .first(); if (doc == null) { return null; } return mapper.convertValue(doc, ${implementation}.class); } #else /** * Find $elementInterface by ${field.Name}. * @param ${field.VarName} * @return Iterator of results */ #if(${field.DefaultField}) @Override #end public Iterable<$elementInterface> findBy${field.NameForMethod}(#fieldtype ${field.VarName}) throws Exception { return this.collection.find(PersistenceFilters.eq("${field.VarName}", ${field.VarName})) .map(doc -> mapper.convertValue(doc, ${implementation}.class)); } #end## if unique #end## if getter and search #end## foreach }