Search in sources :

Example 1 with FilterCriteria

use of org.eclipse.smarthome.core.persistence.FilterCriteria in project smarthome by eclipse.

the class PersistenceManagerImpl method initialize.

/**
 * Handles the "restoreOnStartup" strategy for the item.
 * If the item state is still undefined when entering this method, all persistence configurations are checked,
 * if they have the "restoreOnStartup" strategy configured for the item. If so, the item state will be set
 * to its last persisted value.
 *
 * @param item the item to restore the state for
 */
private void initialize(Item item) {
    // get the last persisted state from the persistence service if no state is yet set
    if (item.getState().equals(UnDefType.NULL) && item instanceof GenericItem) {
        for (Entry<String, PersistenceServiceConfiguration> entry : persistenceServiceConfigs.entrySet()) {
            final String serviceName = entry.getKey();
            final PersistenceServiceConfiguration config = entry.getValue();
            for (SimpleItemConfiguration itemConfig : config.getConfigs()) {
                if (hasStrategy(serviceName, itemConfig, SimpleStrategy.Globals.RESTORE)) {
                    if (appliesToItem(itemConfig, item)) {
                        PersistenceService service = persistenceServices.get(serviceName);
                        if (service instanceof QueryablePersistenceService) {
                            QueryablePersistenceService queryService = (QueryablePersistenceService) service;
                            FilterCriteria filter = new FilterCriteria().setItemName(item.getName()).setPageSize(1);
                            Iterable<HistoricItem> result = queryService.query(filter);
                            Iterator<HistoricItem> it = result.iterator();
                            if (it.hasNext()) {
                                HistoricItem historicItem = it.next();
                                GenericItem genericItem = (GenericItem) item;
                                genericItem.removeStateChangeListener(this);
                                genericItem.setState(historicItem.getState());
                                genericItem.addStateChangeListener(this);
                                logger.debug("Restored item state from '{}' for item '{}' -> '{}'", new Object[] { DateFormat.getDateTimeInstance().format(historicItem.getTimestamp()), item.getName(), historicItem.getState().toString() });
                                return;
                            }
                        } else if (service != null) {
                            logger.warn("Failed to restore item states as persistence service '{}' can not be queried.", serviceName);
                        }
                    }
                }
            }
        }
    }
}
Also used : QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) GenericItem(org.eclipse.smarthome.core.items.GenericItem) SimpleItemConfiguration(org.eclipse.smarthome.core.persistence.SimpleItemConfiguration) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem) PersistenceServiceConfiguration(org.eclipse.smarthome.core.persistence.PersistenceServiceConfiguration)

Example 2 with FilterCriteria

use of org.eclipse.smarthome.core.persistence.FilterCriteria in project smarthome by eclipse.

the class PersistenceResource method deletePersistenceItemData.

private Response deletePersistenceItemData(String serviceId, String itemName, String timeBegin, String timeEnd) {
    // For deleting, we must specify a service id - don't use the default service
    if (serviceId == null || serviceId.length() == 0) {
        logger.debug("Persistence service must be specified for delete operations.");
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service must be specified for delete operations.");
    }
    PersistenceService service = persistenceServiceRegistry.get(serviceId);
    if (service == null) {
        logger.debug("Persistence service not found '{}'.", serviceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not found: " + serviceId);
    }
    if (!(service instanceof ModifiablePersistenceService)) {
        logger.warn("Persistence service not modifiable '{}'.", serviceId);
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Persistence service not modifiable: " + serviceId);
    }
    ModifiablePersistenceService mService = (ModifiablePersistenceService) service;
    if (timeBegin == null | timeEnd == null) {
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "The start and end time must be set");
    }
    ZonedDateTime dateTimeBegin = convertTime(timeBegin);
    ZonedDateTime dateTimeEnd = convertTime(timeEnd);
    if (dateTimeEnd.isBefore(dateTimeBegin)) {
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Start time must be earlier than end time");
    }
    FilterCriteria filter;
    // First, get the value at the start time.
    // This is necessary for values that don't change often otherwise data will start after the start of the graph
    // (or not at all if there's no change during the graph period)
    filter = new FilterCriteria();
    filter.setBeginDate(dateTimeBegin);
    filter.setEndDate(dateTimeEnd);
    filter.setItemName(itemName);
    try {
        mService.remove(filter);
    } catch (IllegalArgumentException e) {
        return JSONResponse.createErrorResponse(Status.BAD_REQUEST, "Invalid filter parameters.");
    }
    return Response.status(Status.OK).build();
}
Also used : PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) ModifiablePersistenceService(org.eclipse.smarthome.core.persistence.ModifiablePersistenceService) ModifiablePersistenceService(org.eclipse.smarthome.core.persistence.ModifiablePersistenceService) ZonedDateTime(java.time.ZonedDateTime) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria)

Example 3 with FilterCriteria

use of org.eclipse.smarthome.core.persistence.FilterCriteria in project smarthome by eclipse.

the class PersistenceExtensions method historicState.

/**
 * Retrieves the historic item for a given <code>item</code> at a certain point in time through a
 * {@link PersistenceService} identified by the <code>serviceId</code>.
 *
 * @param item the item for which to retrieve the historic item
 * @param timestamp the point in time for which the historic item should be retrieved
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return the historic item at the given point in time, or <code>null</code> if no historic item could be found or
 *         if the provided <code>serviceId</code> does not refer to an available
 *         {@link QueryablePersistenceService}
 */
public static HistoricItem historicState(Item item, AbstractInstant timestamp, String serviceId) {
    PersistenceService service = getService(serviceId);
    if (service instanceof QueryablePersistenceService) {
        QueryablePersistenceService qService = (QueryablePersistenceService) service;
        FilterCriteria filter = new FilterCriteria();
        filter.setEndDate(ZonedDateTime.ofInstant(timestamp.toDate().toInstant(), timeZoneProvider.getTimeZone()));
        filter.setItemName(item.getName());
        filter.setPageSize(1);
        filter.setOrdering(Ordering.DESCENDING);
        Iterable<HistoricItem> result = qService.query(filter);
        if (result.iterator().hasNext()) {
            return result.iterator().next();
        } else {
            return null;
        }
    } else {
        LoggerFactory.getLogger(PersistenceExtensions.class).warn("There is no queryable persistence service registered with the id '{}'", serviceId);
        return null;
    }
}
Also used : QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Example 4 with FilterCriteria

use of org.eclipse.smarthome.core.persistence.FilterCriteria in project smarthome by eclipse.

the class PersistenceExtensions method lastUpdate.

/**
 * Query for the last update time of a given <code>item</code>.
 *
 * @param item the item for which the last update time is to be returned
 * @param serviceId the name of the {@link PersistenceService} to use
 * @return last time <code>item</code> was updated, or <code>null</code> if there are no previously
 *         persisted updates or if persistence service given by <code>serviceId</code> does not refer to an
 *         available {@link QueryablePersistenceService}
 */
public static AbstractInstant lastUpdate(Item item, String serviceId) {
    PersistenceService service = getService(serviceId);
    if (service instanceof QueryablePersistenceService) {
        QueryablePersistenceService qService = (QueryablePersistenceService) service;
        FilterCriteria filter = new FilterCriteria();
        filter.setItemName(item.getName());
        filter.setOrdering(Ordering.DESCENDING);
        filter.setPageSize(1);
        Iterable<HistoricItem> result = qService.query(filter);
        if (result.iterator().hasNext()) {
            return new DateTime(result.iterator().next().getTimestamp());
        } else {
            return null;
        }
    } else {
        LoggerFactory.getLogger(PersistenceExtensions.class).warn("There is no queryable persistence service registered with the id '{}'", serviceId);
        return null;
    }
}
Also used : QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) PersistenceService(org.eclipse.smarthome.core.persistence.PersistenceService) QueryablePersistenceService(org.eclipse.smarthome.core.persistence.QueryablePersistenceService) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem) ZonedDateTime(java.time.ZonedDateTime) DateTime(org.joda.time.DateTime)

Example 5 with FilterCriteria

use of org.eclipse.smarthome.core.persistence.FilterCriteria in project smarthome by eclipse.

the class DefaultChartProvider method addItem.

boolean addItem(Chart chart, QueryablePersistenceService service, Date timeBegin, Date timeEnd, Item item, int seriesCounter, ChartTheme chartTheme, int dpi) {
    Color color = chartTheme.getLineColor(seriesCounter);
    // Get the item label
    String label = null;
    if (itemUIRegistry != null) {
        // Get the item label
        label = itemUIRegistry.getLabel(item.getName());
        if (label != null && label.contains("[") && label.contains("]")) {
            label = label.substring(0, label.indexOf('['));
        }
    }
    if (label == null) {
        label = item.getName();
    }
    Iterable<HistoricItem> result;
    FilterCriteria filter;
    // Generate data collections
    List<Date> xData = new ArrayList<Date>();
    List<Number> yData = new ArrayList<Number>();
    // Declare state here so it will hold the last value at the end of the process
    State state = null;
    // First, get the value at the start time.
    // This is necessary for values that don't change often otherwise data will start
    // after the start of the graph (or not at all if there's no change during the graph period)
    filter = new FilterCriteria();
    filter.setEndDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone()));
    filter.setItemName(item.getName());
    filter.setPageSize(1);
    filter.setOrdering(Ordering.DESCENDING);
    result = service.query(filter);
    if (result.iterator().hasNext()) {
        HistoricItem historicItem = result.iterator().next();
        state = historicItem.getState();
        xData.add(timeBegin);
        yData.add(convertData(state));
    }
    // Now, get all the data between the start and end time
    filter.setBeginDate(ZonedDateTime.ofInstant(timeBegin.toInstant(), timeZoneProvider.getTimeZone()));
    filter.setEndDate(ZonedDateTime.ofInstant(timeEnd.toInstant(), timeZoneProvider.getTimeZone()));
    filter.setPageSize(Integer.MAX_VALUE);
    filter.setOrdering(Ordering.ASCENDING);
    // Get the data from the persistence store
    result = service.query(filter);
    Iterator<HistoricItem> it = result.iterator();
    // Iterate through the data
    while (it.hasNext()) {
        HistoricItem historicItem = it.next();
        // to avoid diagonal lines
        if (state instanceof OnOffType || state instanceof OpenClosedType) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(historicItem.getTimestamp());
            cal.add(Calendar.MILLISECOND, -1);
            xData.add(cal.getTime());
            yData.add(convertData(state));
        }
        state = historicItem.getState();
        xData.add(historicItem.getTimestamp());
        yData.add(convertData(state));
    }
    // Lastly, add the final state at the endtime
    if (state != null) {
        xData.add(timeEnd);
        yData.add(convertData(state));
    }
    // The chart engine will throw an exception if there's no data
    if (xData.size() == 0) {
        return false;
    }
    // If there's only 1 data point, plot it again!
    if (xData.size() == 1) {
        xData.add(xData.iterator().next());
        yData.add(yData.iterator().next());
    }
    Series series = chart.addSeries(label, xData, yData);
    float lineWidth = (float) chartTheme.getLineWidth(dpi);
    series.setLineStyle(new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER));
    series.setMarker(SeriesMarker.NONE);
    series.setLineColor(color);
    // We use this to decide whether to put the legend in the top or bottom corner.
    if (yData.iterator().next().floatValue() > ((series.getYMax() - series.getYMin()) / 2 + series.getYMin())) {
        legendPosition++;
    } else {
        legendPosition--;
    }
    return true;
}
Also used : BasicStroke(java.awt.BasicStroke) Color(java.awt.Color) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) FilterCriteria(org.eclipse.smarthome.core.persistence.FilterCriteria) Date(java.util.Date) Series(org.knowm.xchart.Series) OnOffType(org.eclipse.smarthome.core.library.types.OnOffType) State(org.eclipse.smarthome.core.types.State) OpenClosedType(org.eclipse.smarthome.core.library.types.OpenClosedType) HistoricItem(org.eclipse.smarthome.core.persistence.HistoricItem)

Aggregations

FilterCriteria (org.eclipse.smarthome.core.persistence.FilterCriteria)8 PersistenceService (org.eclipse.smarthome.core.persistence.PersistenceService)7 QueryablePersistenceService (org.eclipse.smarthome.core.persistence.QueryablePersistenceService)7 HistoricItem (org.eclipse.smarthome.core.persistence.HistoricItem)6 ZonedDateTime (java.time.ZonedDateTime)3 OnOffType (org.eclipse.smarthome.core.library.types.OnOffType)2 OpenClosedType (org.eclipse.smarthome.core.library.types.OpenClosedType)2 ModifiablePersistenceService (org.eclipse.smarthome.core.persistence.ModifiablePersistenceService)2 State (org.eclipse.smarthome.core.types.State)2 BasicStroke (java.awt.BasicStroke)1 Color (java.awt.Color)1 ArrayList (java.util.ArrayList)1 Calendar (java.util.Calendar)1 Date (java.util.Date)1 GenericItem (org.eclipse.smarthome.core.items.GenericItem)1 PersistenceServiceConfiguration (org.eclipse.smarthome.core.persistence.PersistenceServiceConfiguration)1 SimpleItemConfiguration (org.eclipse.smarthome.core.persistence.SimpleItemConfiguration)1 ItemHistoryDTO (org.eclipse.smarthome.core.persistence.dto.ItemHistoryDTO)1 DateTime (org.joda.time.DateTime)1 Series (org.knowm.xchart.Series)1