All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.elsci.signals.mock.attributes.AttributeDao Maven / Gradle / Ivy

There is a newer version: 20231025.1145-36
Show newest version
package io.elsci.signals.mock.attributes;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import io.elsci.signals.mock.exception.EntityNotFoundException;
import io.elsci.signals.sdk.attributes.Attribute;
import io.elsci.signals.sdk.attributes.AttributeType;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.ArrayList;
import java.util.List;

public class AttributeDao {
    private final MongoClient mongo;
    private final String dbName;
    private final String attributesCollectionName;

    public AttributeDao(MongoClient mongo, String dbName, String attributesCollectionName) {
        this.mongo = mongo;
        this.dbName = dbName;
        this.attributesCollectionName = attributesCollectionName;
    }

    public Attribute save(Attribute a) {
        MongoCollection collection = collection();
        Document d = new Document("_id", a.getId())
                .append("eid", a.getId())
                .append("type", a.getType())
                .append("name", a.getName())
                .append("description", a.getDescription())
                .append("options", a.getOptions());
        collection.insertOne(d);
        return a;
    }

    public List list() {
        List result = new ArrayList<>();
        collection().find().map(AttributeDao::mapFromDocument).forEach(result::add);
        return result;
    }
    public Attribute get(String id) {
        List result = findAttributes(Filters.eq("_id", id));
        if(result.isEmpty())
            throw new EntityNotFoundException(Attribute.class, id);
        return result.get(0);
    }
    public Attribute findByName(String name) {
        List attr = findAttributes(Filters.eq("name", name));
        if(attr.isEmpty())
            return null;
        return attr.get(0);
    }
    private List findAttributes(Bson filter) {
        List result = new ArrayList<>();
        find(filter).map(AttributeDao::mapFromDocument).forEach(result::add);
        return result;
    }
    private FindIterable find(Bson filter) {
        return collection().find(filter);
    }

    private static Attribute mapFromDocument(Document d) {
        return new Attribute(
                d.getString("_id"),
                d.getString("name"),
                AttributeType.valueOf(d.getString("type")),
                d.getString("description"),
                d.getList("options", String.class));
    }
    private MongoCollection collection() {
        return mongo.getDatabase(dbName).getCollection(attributesCollectionName);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy