MongoAccessLog.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.MongoDatabase;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bson.Document;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
*
*/
class MongoAccessLog implements AccessLog {
MongoClient mongo;
String collection;
MongoDatabase mdb;
Logger log;
MongoAccessLog(Logger log, String uri, String collection) {
// "mongodb://user:pass@host:port/db"
MongoClientURI u = new MongoClientURI(uri);
String dbname = u.getDatabase();
if (dbname == null)
dbname = "csip";
mongo = new MongoClient(u);
mdb = mongo.getDatabase(dbname);
this.collection = collection;
this.log = log;
log.log(Level.INFO, "Connected to access log: {0}", uri);
}
@Override
public synchronized void close() throws Exception {
mongo.close();
}
@Override
public void log(JSONObject metainfo) {
if (metainfo == null)
return;
Document doc = new Document();
@SuppressWarnings("unchecked")
Iterator<String> i = metainfo.keys();
while (i.hasNext()) {
try {
String key = i.next();
doc.append(key, metainfo.get(key));
} catch (JSONException ex) {
log.log(Level.WARNING, null, ex);
}
}
mdb.getCollection(collection).insertOne(doc);
if (log.isLoggable(Level.INFO))
log.log(Level.INFO, "logged: {0}", doc.toJson());
}
}