private @NonNullByDefault({}) String url;
private @NonNullByDefault({}) String db;
private @NonNullByDefault({}) String collection;
+ private boolean collectionPerItem;
private boolean initialized = false;
collection = (String) config.get("collection");
logger.debug("MongoDB collection {}", collection);
if (collection == null || collection.isBlank()) {
- logger.warn(
- "The MongoDB database collection is missing - please configure the mongodb:collection parameter.");
- return;
+ collectionPerItem = false;
+ } else {
+ collectionPerItem = true;
}
disconnectFromDatabase();
}
String realName = item.getName();
+
+ // If collection Per Item is active, connect to the item Collection
+ if (collectionPerItem) {
+ connectToCollection(realName);
+ }
+
String name = (alias != null) ? alias : realName;
Object value = this.convertValue(item.getState());
obj.put(FIELD_VALUE, value);
this.mongoCollection.save(obj);
+ // If collection Per Item is active, disconnect after save.
+ if (collectionPerItem) {
+ disconnectFromCollection();
+ }
+
logger.debug("MongoDB save {}={}", name, value);
}
try {
logger.debug("Connect MongoDB");
this.cl = new MongoClient(new MongoClientURI(this.url));
- mongoCollection = cl.getDB(this.db).getCollection(this.collection);
+ if (collectionPerItem) {
+ mongoCollection = cl.getDB(this.db).getCollection(this.collection);
+
+ BasicDBObject idx = new BasicDBObject();
+ idx.append(FIELD_TIMESTAMP, 1).append(FIELD_ITEM, 1);
+ this.mongoCollection.createIndex(idx);
+ }
- BasicDBObject idx = new BasicDBObject();
- idx.append(FIELD_TIMESTAMP, 1).append(FIELD_ITEM, 1);
- this.mongoCollection.createIndex(idx);
logger.debug("Connect MongoDB ... done");
} catch (Exception e) {
logger.error("Failed to connect to database {}", this.url);
}
}
+ /**
+ * Connects to the Collection
+ */
+ private void connectToCollection(String collectionName) {
+ try {
+ mongoCollection = cl.getDB(this.db).getCollection(collectionName);
+
+ BasicDBObject idx = new BasicDBObject();
+ idx.append(FIELD_TIMESTAMP, 1).append(FIELD_ITEM, 1);
+ this.mongoCollection.createIndex(idx);
+ } catch (Exception e) {
+ logger.error("Failed to connect to collection {}", collectionName);
+ throw new RuntimeException("Cannot connect to collection", e);
+ }
+ }
+
+ /**
+ * Disconnects from the Collection
+ */
+ private void disconnectFromCollection() {
+ this.mongoCollection = null;
+ }
+
/**
* Disconnects from the database
*/
}
String name = filter.getItemName();
+
+ // If collection Per Item is active, connect to the item Collection
+ if (collectionPerItem) {
+ connectToCollection(name);
+ }
Item item = getItem(name);
List<HistoricItem> items = new ArrayList<>();
ZonedDateTime.ofInstant(obj.getDate(FIELD_TIMESTAMP).toInstant(), ZoneId.systemDefault())));
}
+ // If collection Per Item is active, disconnect after save.
+ if (collectionPerItem) {
+ disconnectFromCollection();
+ }
return items;
}