MongoResultStore.java [src/csip] Revision: 71821307bfe742c00c6dc582c171224a9ac59935  Date: Fri Apr 21 11:46:19 MDT 2017
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2017, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;

/**
 *
 */
class MongoResultStore implements ResultStore {

    MongoClient mongo;
    MongoDatabase db;
    static final String RESULTS = "results";


    MongoResultStore(String uri) {
        MongoClientURI u = new MongoClientURI(uri);
        String dbname = u.getDatabase();
        if (dbname == null) {
            dbname = "csip";
        }
        mongo = new MongoClient(u);
        db = mongo.getDatabase(dbname);
        Config.LOG.info("Connected to mongo result store : " + uri);
    }


    @Override
    public synchronized String getResult(String digest) {
        FindIterable<Document> r = db.getCollection(RESULTS).find(new Document("_id", digest));
        Document o = r.first();
        if (o != null) {
            return o.getString("result");
        } else {
            Config.LOG.warning("No previous result for : " + digest);
            return null;
        }
    }


    @Override
    public synchronized void putResult(String digest, String result) {
        Document doc = new Document();
        doc.append("_id", digest);
        doc.append("result", result);
        UpdateOptions opt = new UpdateOptions();
        opt.upsert(true);
        MongoCollection<Document> c = db.getCollection(RESULTS);
        c.replaceOne(new Document("_id", digest), doc, opt);
        Config.LOG.info("put result: " + digest + " " + doc.toJson());
    }


    @Override
    public synchronized void purge() {
        db.getCollection(RESULTS).drop();
    }


    @Override
    public void shutdown() throws Exception {
        mongo.close();
    }
    
}