use of org.openhab.core.persistence.HistoricItem in project openhab1-addons by openhab.
the class MongoDBPersistenceService method query.
@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
if (!initialized) {
return Collections.emptyList();
}
if (!isConnected()) {
connectToDatabase();
}
if (!isConnected()) {
return Collections.emptyList();
}
String name = filter.getItemName();
Item item = getItem(name);
List<HistoricItem> items = new ArrayList<HistoricItem>();
DBObject query = new BasicDBObject();
if (filter.getItemName() != null) {
query.put(FIELD_ITEM, filter.getItemName());
}
if (filter.getState() != null && filter.getOperator() != null) {
String op = convertOperator(filter.getOperator());
Object value = convertValue(filter.getState());
query.put(FIELD_VALUE, new BasicDBObject(op, value));
}
if (filter.getBeginDate() != null) {
query.put(FIELD_TIMESTAMP, new BasicDBObject("$gte", filter.getBeginDate()));
}
if (filter.getEndDate() != null) {
query.put(FIELD_TIMESTAMP, new BasicDBObject("$lte", filter.getEndDate()));
}
Integer sortDir = (filter.getOrdering() == Ordering.ASCENDING) ? 1 : -1;
DBCursor cursor = this.mongoCollection.find(query).sort(new BasicDBObject(FIELD_TIMESTAMP, sortDir)).skip(filter.getPageNumber() * filter.getPageSize()).limit(filter.getPageSize());
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
final State state;
if (item instanceof NumberItem) {
state = new DecimalType(obj.getDouble(FIELD_VALUE));
} else if (item instanceof DimmerItem) {
state = new PercentType(obj.getInt(FIELD_VALUE));
} else if (item instanceof SwitchItem) {
state = OnOffType.valueOf(obj.getString(FIELD_VALUE));
} else if (item instanceof ContactItem) {
state = OpenClosedType.valueOf(obj.getString(FIELD_VALUE));
} else if (item instanceof RollershutterItem) {
state = new PercentType(obj.getInt(FIELD_VALUE));
} else if (item instanceof ColorItem) {
state = new HSBType(obj.getString(FIELD_VALUE));
} else if (item instanceof DateTimeItem) {
Calendar cal = Calendar.getInstance();
cal.setTime(obj.getDate(FIELD_VALUE));
state = new DateTimeType(cal);
} else {
state = new StringType(obj.getString(FIELD_VALUE));
}
items.add(new MongoDBItem(name, state, obj.getDate(FIELD_TIMESTAMP)));
}
return items;
}
use of org.openhab.core.persistence.HistoricItem in project openhab1-addons by openhab.
the class MysqlPersistenceService method query.
@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
if (!initialized) {
logger.debug("Query aborted on item {} - mySQL not initialised!", filter.getItemName());
return Collections.emptyList();
}
if (!isConnected()) {
connectToDatabase();
}
if (!isConnected()) {
logger.debug("Query aborted on item {} - mySQL not connected!", filter.getItemName());
return Collections.emptyList();
}
SimpleDateFormat mysqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Get the item name from the filter
// Also get the Item object so we can determine the type
Item item = null;
String itemName = filter.getItemName();
logger.debug("mySQL query: item is {}", itemName);
try {
if (itemRegistry != null) {
item = itemRegistry.getItem(itemName);
}
} catch (ItemNotFoundException e1) {
logger.error("Unable to get item type for {}", itemName);
// Set type to null - data will be returned as StringType
item = null;
}
if (item instanceof GroupItem) {
// For Group Items is BaseItem needed to get correct Type of Value.
item = GroupItem.class.cast(item).getBaseItem();
}
String table = sqlTables.get(itemName);
if (table == null) {
logger.error("mySQL: Unable to find table for query '{}'.", itemName);
return Collections.emptyList();
}
String filterString = new String();
if (filter.getBeginDate() != null) {
if (filterString.isEmpty()) {
filterString += " WHERE";
} else {
filterString += " AND";
}
filterString += " TIME>'" + mysqlDateFormat.format(filter.getBeginDate()) + "'";
}
if (filter.getEndDate() != null) {
if (filterString.isEmpty()) {
filterString += " WHERE";
} else {
filterString += " AND";
}
filterString += " TIME<'" + mysqlDateFormat.format(filter.getEndDate().getTime()) + "'";
}
if (filter.getOrdering() == Ordering.ASCENDING) {
filterString += " ORDER BY Time ASC";
} else {
filterString += " ORDER BY Time DESC";
}
if (filter.getPageSize() != 0x7fffffff) {
filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize();
}
try {
long timerStart = System.currentTimeMillis();
// Retrieve the table array
Statement st = connection.createStatement();
String queryString = new String();
queryString = "SELECT Time, Value FROM " + table;
if (!filterString.isEmpty()) {
queryString += filterString;
}
logger.debug("mySQL: query:" + queryString);
// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery(queryString);
long count = 0;
List<HistoricItem> items = new ArrayList<HistoricItem>();
State state;
while (rs.next()) {
count++;
if (item instanceof NumberItem) {
state = new DecimalType(rs.getDouble(2));
} else if (item instanceof ColorItem) {
state = new HSBType(rs.getString(2));
} else if (item instanceof DimmerItem) {
state = new PercentType(rs.getInt(2));
} else if (item instanceof SwitchItem) {
state = OnOffType.valueOf(rs.getString(2));
} else if (item instanceof ContactItem) {
state = OpenClosedType.valueOf(rs.getString(2));
} else if (item instanceof RollershutterItem) {
state = new PercentType(rs.getInt(2));
} else if (item instanceof DateTimeItem) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(rs.getTimestamp(2).getTime());
state = new DateTimeType(calendar);
} else {
state = new StringType(rs.getString(2));
}
MysqlItem mysqlItem = new MysqlItem(itemName, state, rs.getTimestamp(1));
items.add(mysqlItem);
}
rs.close();
st.close();
long timerStop = System.currentTimeMillis();
logger.debug("mySQL: query returned {} rows in {}ms", count, timerStop - timerStart);
// Success
errCnt = 0;
return items;
} catch (SQLException e) {
errCnt++;
logger.error("mySQL: Error running querying : ", e.getMessage());
}
return null;
}
use of org.openhab.core.persistence.HistoricItem in project openhab1-addons by openhab.
the class RRD4jService method query.
@Override
public Iterable<HistoricItem> query(FilterCriteria filter) {
String itemName = filter.getItemName();
RrdDb db = getDB(itemName);
if (db != null) {
ConsolFun consolidationFunction = getConsolidationFunction(db);
long start = 0L;
long end = filter.getEndDate() == null ? System.currentTimeMillis() / 1000 : filter.getEndDate().getTime() / 1000;
try {
if (filter.getBeginDate() == null) {
// want to support
if (filter.getOrdering() == Ordering.DESCENDING && filter.getPageSize() == 1 && filter.getPageNumber() == 0) {
if (filter.getEndDate() == null) {
// we are asked only for the most recent value!
double lastValue = db.getLastDatasourceValue(DATASOURCE_STATE);
if (!Double.isNaN(lastValue)) {
HistoricItem rrd4jItem = new RRD4jItem(itemName, mapToState(lastValue, itemName), new Date(db.getLastArchiveUpdateTime() * 1000));
return Collections.singletonList(rrd4jItem);
} else {
return Collections.emptyList();
}
} else {
start = end;
}
} else {
throw new UnsupportedOperationException("rrd4j does not allow querys without a begin date, " + "unless order is descending and a single value is requested");
}
} else {
start = filter.getBeginDate().getTime() / 1000;
}
FetchRequest request = db.createFetchRequest(consolidationFunction, start, end, 1);
List<HistoricItem> items = new ArrayList<HistoricItem>();
FetchData result = request.fetchData();
long ts = result.getFirstTimestamp();
long step = result.getRowCount() > 1 ? result.getStep() : 0;
for (double value : result.getValues(DATASOURCE_STATE)) {
if (!Double.isNaN(value) && (((ts >= start) && (ts <= end)) || (start == end))) {
RRD4jItem rrd4jItem = new RRD4jItem(itemName, mapToState(value, itemName), new Date(ts * 1000));
items.add(rrd4jItem);
}
ts += step;
}
return items;
} catch (IOException e) {
logger.warn("Could not query rrd4j database for item '{}': {}", itemName, e.getMessage());
}
}
return Collections.emptyList();
}
use of org.openhab.core.persistence.HistoricItem in project openhab1-addons by openhab.
the class JpaHistoricItem method fromResultList.
/**
* This method maps a jpa result item to this historic item.
*
* @param jpaQueryResult the result which jpa items
* @param item used for query information, like the state (State)
* @return list of historic items
*/
public static List<HistoricItem> fromResultList(List<JpaPersistentItem> jpaQueryResult, Item item) {
List<HistoricItem> ret = new ArrayList<HistoricItem>();
for (JpaPersistentItem i : jpaQueryResult) {
HistoricItem hi = fromPersistedItem(i, item);
ret.add(hi);
}
return ret;
}
Aggregations