]> git.basschouten.com Git - openhab-addons.git/blob
bf8103d22bba32b67e29ea3a14dd8a22f5516c2a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.persistence.jdbc.internal;
14
15 import java.util.List;
16 import java.util.Locale;
17 import java.util.Map;
18 import java.util.Set;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.config.core.ConfigurableService;
23 import org.openhab.core.i18n.TimeZoneProvider;
24 import org.openhab.core.items.GroupItem;
25 import org.openhab.core.items.Item;
26 import org.openhab.core.items.ItemNotFoundException;
27 import org.openhab.core.items.ItemRegistry;
28 import org.openhab.core.persistence.FilterCriteria;
29 import org.openhab.core.persistence.HistoricItem;
30 import org.openhab.core.persistence.PersistenceItemInfo;
31 import org.openhab.core.persistence.PersistenceService;
32 import org.openhab.core.persistence.QueryablePersistenceService;
33 import org.openhab.core.persistence.strategy.PersistenceStrategy;
34 import org.openhab.core.types.UnDefType;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.Constants;
37 import org.osgi.service.component.annotations.Activate;
38 import org.osgi.service.component.annotations.Component;
39 import org.osgi.service.component.annotations.Deactivate;
40 import org.osgi.service.component.annotations.Reference;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * This is the implementation of the JDBC {@link PersistenceService}.
46  *
47  * @author Helmut Lehmeyer - Initial contribution
48  * @author Kai Kreuzer - Migration to 3.x
49  */
50 @NonNullByDefault
51 @Component(service = { PersistenceService.class,
52         QueryablePersistenceService.class }, configurationPid = "org.openhab.jdbc", //
53         property = Constants.SERVICE_PID + "=org.openhab.jdbc")
54 @ConfigurableService(category = "persistence", label = "JDBC Persistence Service", description_uri = JdbcPersistenceService.CONFIG_URI)
55 public class JdbcPersistenceService extends JdbcMapper implements QueryablePersistenceService {
56
57     protected static final String CONFIG_URI = "persistence:jdbc";
58
59     private final Logger logger = LoggerFactory.getLogger(JdbcPersistenceService.class);
60
61     private final ItemRegistry itemRegistry;
62
63     @Activate
64     public JdbcPersistenceService(final @Reference ItemRegistry itemRegistry,
65             final @Reference TimeZoneProvider timeZoneProvider) {
66         super(timeZoneProvider);
67         this.itemRegistry = itemRegistry;
68     }
69
70     /**
71      * Called by the SCR to activate the component with its configuration read
72      * from CAS
73      *
74      * @param bundleContext
75      *            BundleContext of the Bundle that defines this component
76      * @param configuration
77      *            Configuration properties for this component obtained from the
78      *            ConfigAdmin service
79      */
80     @Activate
81     public void activate(BundleContext bundleContext, Map<Object, Object> configuration) {
82         logger.debug("JDBC::activate: persistence service activated");
83         updateConfig(configuration);
84     }
85
86     /**
87      * Called by the SCR to deactivate the component when either the
88      * configuration is removed or mandatory references are no longer satisfied
89      * or the component has simply been stopped.
90      *
91      * @param reason
92      *            Reason code for the deactivation:<br>
93      *            <ul>
94      *            <li>0 – Unspecified
95      *            <li>1 – The component was disabled
96      *            <li>2 – A reference became unsatisfied
97      *            <li>3 – A configuration was changed
98      *            <li>4 – A configuration was deleted
99      *            <li>5 – The component was disposed
100      *            <li>6 – The bundle was stopped
101      *            </ul>
102      */
103     @Deactivate
104     public void deactivate(final int reason) {
105         logger.debug("JDBC::deactivate:  persistence bundle stopping. Disconnecting from database. reason={}", reason);
106         // closeConnection();
107         initialized = false;
108     }
109
110     @Override
111     public String getId() {
112         logger.debug("JDBC::getName: returning name 'jdbc' for queryable persistence service.");
113         return "jdbc";
114     }
115
116     @Override
117     public String getLabel(@Nullable Locale locale) {
118         return "JDBC";
119     }
120
121     @Override
122     public void store(Item item) {
123         store(item, null);
124     }
125
126     /**
127      * @{inheritDoc
128      */
129     @Override
130     public void store(Item item, @Nullable String alias) {
131         // Do not store undefined/uninitialized data
132         if (item.getState() instanceof UnDefType) {
133             logger.debug("JDBC::store: ignore Item '{}' because it is UnDefType", item.getName());
134             return;
135         }
136         if (!checkDBAccessability()) {
137             logger.warn(
138                     "JDBC::store:  No connection to database. Cannot persist item '{}'! Will retry connecting to database when error count:{} equals errReconnectThreshold:{}",
139                     item, errCnt, conf.getErrReconnectThreshold());
140             return;
141         }
142         long timerStart = System.currentTimeMillis();
143         storeItemValue(item);
144         logger.debug("JDBC: Stored item '{}' as '{}' in SQL database at {} in {} ms.", item.getName(), item.getState(),
145                 new java.util.Date(), System.currentTimeMillis() - timerStart);
146     }
147
148     @Override
149     public Set<PersistenceItemInfo> getItemInfo() {
150         return getItems();
151     }
152
153     /**
154      * Queries the {@link PersistenceService} for data with a given filter
155      * criteria
156      *
157      * @param filter
158      *            the filter to apply to the query
159      * @return a time series of items
160      */
161     @Override
162     public Iterable<HistoricItem> query(FilterCriteria filter) {
163         if (!checkDBAccessability()) {
164             logger.warn("JDBC::query: database not connected, query aborted for item '{}'", filter.getItemName());
165             return List.of();
166         }
167
168         // Get the item name from the filter
169         // Also get the Item object so we can determine the type
170         Item item = null;
171         String itemName = filter.getItemName();
172         logger.debug("JDBC::query: item is {}", itemName);
173         try {
174             item = itemRegistry.getItem(itemName);
175         } catch (ItemNotFoundException e1) {
176             logger.error("JDBC::query: unable to get item for itemName: '{}'. Ignore and give up!", itemName);
177             return List.of();
178         }
179
180         if (item instanceof GroupItem) {
181             // For Group Item is BaseItem needed to get correct Type of Value.
182             item = GroupItem.class.cast(item).getBaseItem();
183             logger.debug("JDBC::query: item is instanceof GroupItem '{}'", itemName);
184             if (item == null) {
185                 logger.debug("JDBC::query: BaseItem of GroupItem is null. Ignore and give up!");
186                 return List.of();
187             }
188             if (item instanceof GroupItem) {
189                 logger.debug("JDBC::query: BaseItem of GroupItem is a GroupItem too. Ignore and give up!");
190                 return List.of();
191             }
192         }
193
194         String table = sqlTables.get(itemName);
195         if (table == null) {
196             logger.debug("JDBC::query: unable to find table for item with name: '{}', no data in database.", itemName);
197             return List.of();
198         }
199
200         long timerStart = System.currentTimeMillis();
201         List<HistoricItem> items = getHistItemFilterQuery(filter, conf.getNumberDecimalcount(), table, item);
202         if (logger.isDebugEnabled()) {
203             logger.debug("JDBC: Query for item '{}' returned {} rows in {} ms", itemName, items.size(),
204                     System.currentTimeMillis() - timerStart);
205         }
206
207         // Success
208         errCnt = 0;
209         return items;
210     }
211
212     public void updateConfig(Map<Object, Object> configuration) {
213         logger.debug("JDBC::updateConfig");
214
215         conf = new JdbcConfiguration(configuration);
216         if (conf.valid && checkDBAccessability()) {
217             checkDBSchema();
218             // connection has been established ... initialization completed!
219             initialized = true;
220         } else {
221             initialized = false;
222         }
223
224         logger.debug("JDBC::updateConfig: configuration complete for service={}.", getId());
225     }
226
227     @Override
228     public List<PersistenceStrategy> getDefaultStrategies() {
229         return List.of(PersistenceStrategy.Globals.CHANGE);
230     }
231 }