MongoResultStore.java [src/csip] Revision:   Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2022, 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.BsonDocument;
import org.bson.BsonInt32;
import org.bson.Document;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;

/**
 *
 */
class MongoResultStore implements ResultStore {

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

  static final BsonDocument ping = new BsonDocument("ping", new BsonInt32(1));


  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);
  }


  private boolean isAvailable() {
    try {
      Document d = db.runCommand(ping);
      return true;
    } catch (Exception E) {
      Config.LOG.info("ResultStore unavailable.");
      return false;
    }
  }


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


  @Override
  public synchronized void putResult(String digest, JSONArray result) {
    if (!isAvailable()) {
      return;
    }
    Document doc = new Document();
    doc.append("_id", digest);
    doc.append("result", result.toString());
    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 clear() {
    if (!isAvailable()) {
      return;
    }
    db.getCollection(RESULTS).drop();
  }


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

}