2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.persistence.dynamodb.internal;
15 import java.lang.reflect.InvocationTargetException;
17 import java.time.Duration;
18 import java.time.Instant;
19 import java.time.ZonedDateTime;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Locale;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.ThreadPoolExecutor;
31 import java.util.stream.Collectors;
33 import javax.measure.Unit;
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.core.common.ThreadPoolManager;
38 import org.openhab.core.config.core.ConfigurableService;
39 import org.openhab.core.items.GenericItem;
40 import org.openhab.core.items.GroupItem;
41 import org.openhab.core.items.Item;
42 import org.openhab.core.items.ItemNotFoundException;
43 import org.openhab.core.items.ItemRegistry;
44 import org.openhab.core.library.items.NumberItem;
45 import org.openhab.core.library.types.QuantityType;
46 import org.openhab.core.persistence.FilterCriteria;
47 import org.openhab.core.persistence.HistoricItem;
48 import org.openhab.core.persistence.PersistenceItemInfo;
49 import org.openhab.core.persistence.PersistenceService;
50 import org.openhab.core.persistence.QueryablePersistenceService;
51 import org.openhab.core.persistence.strategy.PersistenceStrategy;
52 import org.openhab.core.types.State;
53 import org.openhab.core.types.UnDefType;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.Constants;
56 import org.osgi.service.component.annotations.Activate;
57 import org.osgi.service.component.annotations.Component;
58 import org.osgi.service.component.annotations.Deactivate;
59 import org.osgi.service.component.annotations.Reference;
60 import org.reactivestreams.Subscriber;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
65 import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
66 import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
67 import software.amazon.awssdk.core.async.SdkPublisher;
68 import software.amazon.awssdk.core.client.config.ClientAsyncConfiguration;
69 import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
70 import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
71 import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
72 import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
73 import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
74 import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest;
75 import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
76 import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
77 import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClientBuilder;
78 import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
81 * This is the implementation of the DynamoDB {@link PersistenceService}. It persists item values
82 * using the <a href="https://aws.amazon.com/dynamodb/">Amazon DynamoDB</a> database. The states (
83 * {@link State}) of an {@link Item} are persisted in DynamoDB tables.
85 * The service creates tables automatically, one for numbers, and one for strings.
87 * @see AbstractDynamoDBItem.fromState for details how different items are persisted
89 * @author Sami Salonen - Initial contribution
90 * @author Kai Kreuzer - Migration to 3.x
94 @Component(service = { PersistenceService.class,
95 QueryablePersistenceService.class }, configurationPid = "org.openhab.dynamodb", //
96 property = Constants.SERVICE_PID + "=org.openhab.dynamodb")
97 @ConfigurableService(category = "persistence", label = "DynamoDB Persistence Service", description_uri = DynamoDBPersistenceService.CONFIG_URI)
98 public class DynamoDBPersistenceService implements QueryablePersistenceService {
100 private static final int MAX_CONCURRENCY = 100;
102 protected static final String CONFIG_URI = "persistence:dynamodb";
104 private static final String DYNAMODB_THREADPOOL_NAME = "dynamodbPersistenceService";
106 private ItemRegistry itemRegistry;
107 private @Nullable DynamoDbEnhancedAsyncClient client;
108 private @Nullable DynamoDbAsyncClient lowLevelClient;
109 private static final Logger logger = LoggerFactory.getLogger(DynamoDBPersistenceService.class);
110 private boolean isProperlyConfigured;
111 private @Nullable DynamoDBConfig dbConfig;
112 private @Nullable DynamoDBTableNameResolver tableNameResolver;
113 private final ExecutorService executor = ThreadPoolManager.getPool(DYNAMODB_THREADPOOL_NAME);
114 private static final Duration TIMEOUT_API_CALL = Duration.ofSeconds(60);
115 private static final Duration TIMEOUT_API_CALL_ATTEMPT = Duration.ofSeconds(5);
116 private Map<Class<? extends DynamoDBItem<?>>, DynamoDbAsyncTable<? extends DynamoDBItem<?>>> tableCache = new ConcurrentHashMap<>(
119 private @Nullable URI endpointOverride;
121 void overrideConfig(AwsRequestOverrideConfiguration.Builder config) {
122 config.apiCallAttemptTimeout(TIMEOUT_API_CALL_ATTEMPT).apiCallTimeout(TIMEOUT_API_CALL);
125 void overrideConfig(ClientOverrideConfiguration.Builder config) {
126 DynamoDBConfig localDbConfig = dbConfig;
127 config.apiCallAttemptTimeout(TIMEOUT_API_CALL_ATTEMPT).apiCallTimeout(TIMEOUT_API_CALL);
128 if (localDbConfig != null) {
129 localDbConfig.getRetryPolicy().ifPresent(config::retryPolicy);
134 public DynamoDBPersistenceService(final @Reference ItemRegistry itemRegistry) {
135 this.itemRegistry = itemRegistry;
141 DynamoDBPersistenceService(final ItemRegistry itemRegistry, @Nullable URI endpointOverride) {
142 this.itemRegistry = itemRegistry;
143 this.endpointOverride = endpointOverride;
150 URI getEndpointOverride() {
151 return endpointOverride;
155 DynamoDbAsyncClient getLowLevelClient() {
156 return lowLevelClient;
159 ExecutorService getExecutor() {
164 DynamoDBTableNameResolver getTableNameResolver() {
165 return tableNameResolver;
169 DynamoDBConfig getDbConfig() {
174 public void activate(final @Nullable BundleContext bundleContext, final Map<String, Object> config) {
176 DynamoDBConfig localDbConfig = dbConfig = DynamoDBConfig.fromConfig(config);
177 if (localDbConfig == null) {
178 // Configuration was invalid. Abort service activation.
179 // Error is already logger in fromConfig.
182 tableNameResolver = new DynamoDBTableNameResolver(localDbConfig.getTableRevision(), localDbConfig.getTable(),
183 localDbConfig.getTablePrefixLegacy());
185 if (!ensureClient()) {
186 logger.error("Error creating dynamodb database client. Aborting service activation.");
189 } catch (Exception e) {
190 logger.error("Error constructing dynamodb client", e);
194 isProperlyConfigured = true;
195 logger.debug("dynamodb persistence service activated");
199 public void deactivate() {
200 logger.debug("dynamodb persistence service deactivated");
201 logIfManyQueuedTasks();
206 * Initializes Dynamo DB client and determines schema
208 * If construction fails, error is logged and false is returned.
210 * @return whether initialization was successful.
212 private boolean ensureClient() {
213 DynamoDBConfig localDbConfig = dbConfig;
214 if (localDbConfig == null) {
217 if (client == null) {
219 synchronized (this) {
220 if (this.client != null) {
223 DynamoDbAsyncClientBuilder lowlevelClientBuilder = DynamoDbAsyncClient.builder()
224 .defaultsMode(DefaultsMode.STANDARD)
225 .credentialsProvider(StaticCredentialsProvider.create(localDbConfig.getCredentials()))
226 .httpClient(NettyNioAsyncHttpClient.builder().maxConcurrency(MAX_CONCURRENCY).build())
228 ClientAsyncConfiguration.builder()
229 .advancedOption(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR,
232 .overrideConfiguration(this::overrideConfig).region(localDbConfig.getRegion());
233 if (endpointOverride != null) {
234 logger.debug("DynamoDB has been overriden to {}", endpointOverride);
235 lowlevelClientBuilder.endpointOverride(endpointOverride);
237 DynamoDbAsyncClient lowlevelClient = lowlevelClientBuilder.build();
238 client = DynamoDbEnhancedAsyncClient.builder().dynamoDbClient(lowlevelClient).build();
239 this.lowLevelClient = lowlevelClient;
241 } catch (Exception e) {
242 logger.error("Error constructing dynamodb client", e);
249 private CompletableFuture<Boolean> resolveTableSchema() {
250 DynamoDBTableNameResolver localTableNameResolver = tableNameResolver;
251 DynamoDbAsyncClient localLowLevelClient = lowLevelClient;
252 if (localTableNameResolver == null || localLowLevelClient == null) {
253 throw new IllegalStateException("tableNameResolver or localLowLevelClient not available");
255 if (localTableNameResolver.isFullyResolved()) {
256 return CompletableFuture.completedFuture(true);
258 synchronized (localTableNameResolver) {
259 if (localTableNameResolver.isFullyResolved()) {
260 return CompletableFuture.completedFuture(true);
262 return localTableNameResolver.resolveSchema(localLowLevelClient,
263 b -> b.overrideConfiguration(this::overrideConfig), executor).thenApplyAsync(resolved -> {
264 if (resolved && localTableNameResolver.getTableSchema() == ExpectedTableSchema.LEGACY) {
266 "Using legacy table format. Is it recommended to migrate to the new table format: specify the 'table' parameter and unset the old 'tablePrefix' parameter.");
274 private <T extends DynamoDBItem<?>> DynamoDbAsyncTable<T> getTable(Class<T> dtoClass) {
275 DynamoDbEnhancedAsyncClient localClient = client;
276 DynamoDBTableNameResolver localTableNameResolver = tableNameResolver;
277 if (!ensureClient() || localClient == null || localTableNameResolver == null) {
278 throw new IllegalStateException("Client not ready");
280 ExpectedTableSchema expectedTableSchemaRevision = localTableNameResolver.getTableSchema();
281 String tableName = localTableNameResolver.fromClass(dtoClass);
282 final TableSchema<T> schema = getDynamoDBTableSchema(dtoClass, expectedTableSchemaRevision);
283 @SuppressWarnings("unchecked") // OK since this is the only place tableCache is populated
284 DynamoDbAsyncTable<T> table = (DynamoDbAsyncTable<T>) tableCache.computeIfAbsent(dtoClass, clz -> {
285 return localClient.table(tableName, schema);
288 // Invariant. To make null checker happy
289 throw new IllegalStateException();
294 private static <T extends DynamoDBItem<?>> TableSchema<T> getDynamoDBTableSchema(Class<T> dtoClass,
295 ExpectedTableSchema expectedTableSchemaRevision) {
296 if (dtoClass.equals(DynamoDBBigDecimalItem.class)) {
297 @SuppressWarnings("unchecked") // OK thanks to above conditional
298 TableSchema<T> schema = (TableSchema<T>) (expectedTableSchemaRevision == ExpectedTableSchema.NEW
299 ? DynamoDBBigDecimalItem.TABLE_SCHEMA_NEW
300 : DynamoDBBigDecimalItem.TABLE_SCHEMA_LEGACY);
302 } else if (dtoClass.equals(DynamoDBStringItem.class)) {
303 @SuppressWarnings("unchecked") // OK thanks to above conditional
304 TableSchema<T> schema = (TableSchema<T>) (expectedTableSchemaRevision == ExpectedTableSchema.NEW
305 ? DynamoDBStringItem.TABLE_SCHEMA_NEW
306 : DynamoDBStringItem.TABLE_SCHEMA_LEGACY);
309 throw new IllegalStateException("Unknown DTO class. Bug");
313 private void disconnect() {
314 DynamoDbAsyncClient localLowLevelClient = lowLevelClient;
315 if (client == null || localLowLevelClient == null) {
318 localLowLevelClient.close();
319 lowLevelClient = null;
322 tableNameResolver = null;
323 isProperlyConfigured = false;
327 protected boolean isReadyToStore() {
328 return isProperlyConfigured && ensureClient();
332 public String getId() {
337 public String getLabel(@Nullable Locale locale) {
342 public Set<PersistenceItemInfo> getItemInfo() {
343 return Collections.emptySet();
347 public Iterable<HistoricItem> query(FilterCriteria filter) {
348 logIfManyQueuedTasks();
349 Instant start = Instant.now();
350 String filterDescription = filterToString(filter);
351 logger.trace("Got a query with filter {}", filterDescription);
352 DynamoDbEnhancedAsyncClient localClient = client;
353 DynamoDBTableNameResolver localTableNameResolver = tableNameResolver;
354 if (!isProperlyConfigured) {
355 logger.debug("Configuration for dynamodb not yet loaded or broken. Returning empty query results.");
356 return Collections.emptyList();
358 if (!ensureClient() || localClient == null || localTableNameResolver == null) {
359 logger.warn("DynamoDB not connected. Returning empty query results.");
360 return Collections.emptyList();
364 // Resolve unclear table schema if needed
367 Boolean resolved = resolveTableSchema().get();
369 logger.warn("Table schema not resolved, cannot query data.");
370 return Collections.emptyList();
372 } catch (InterruptedException e) {
373 logger.warn("Table schema resolution interrupted, cannot query data");
374 return Collections.emptyList();
375 } catch (ExecutionException e) {
376 Throwable cause = e.getCause();
377 logger.warn("Table schema resolution errored, cannot query data: {} {}",
378 cause == null ? e.getClass().getSimpleName() : cause.getClass().getSimpleName(),
379 cause == null ? e.getMessage() : cause.getMessage());
380 return Collections.emptyList();
384 // Proceed with query
386 String itemName = filter.getItemName();
387 Item item = getItemFromRegistry(itemName);
389 logger.warn("Could not get item {} from registry! Returning empty query results.", itemName);
390 return Collections.emptyList();
392 if (item instanceof GroupItem) {
393 item = ((GroupItem) item).getBaseItem();
394 logger.debug("Item is instanceof GroupItem '{}'", itemName);
396 logger.debug("BaseItem of GroupItem is null. Ignore and give up!");
397 return Collections.emptyList();
399 if (item instanceof GroupItem) {
400 logger.debug("BaseItem of GroupItem is a GroupItem too. Ignore and give up!");
401 return Collections.emptyList();
404 boolean legacy = localTableNameResolver.getTableSchema() == ExpectedTableSchema.LEGACY;
405 Class<? extends DynamoDBItem<?>> dtoClass = AbstractDynamoDBItem.getDynamoItemClass(item.getClass(),
407 String tableName = localTableNameResolver.fromClass(dtoClass);
408 DynamoDbAsyncTable<? extends DynamoDBItem<?>> table = getTable(dtoClass);
409 logger.debug("Item {} (of type {}) will be tried to query using DTO class {} from table {}", itemName,
410 item.getClass().getSimpleName(), dtoClass.getSimpleName(), tableName);
412 QueryEnhancedRequest queryExpression = DynamoDBQueryUtils.createQueryExpression(dtoClass,
413 localTableNameResolver.getTableSchema(), item, filter);
415 CompletableFuture<List<DynamoDBItem<?>>> itemsFuture = new CompletableFuture<>();
416 final SdkPublisher<? extends DynamoDBItem<?>> itemPublisher = table.query(queryExpression).items();
417 Subscriber<DynamoDBItem<?>> pageSubscriber = new PageOfInterestSubscriber<DynamoDBItem<?>>(itemsFuture,
418 filter.getPageNumber(), filter.getPageSize());
419 itemPublisher.subscribe(pageSubscriber);
420 // NumberItem.getUnit() is expensive, we avoid calling it in the loop
421 // by fetching the unit here.
422 final Item localItem = item;
423 final Unit<?> itemUnit = localItem instanceof NumberItem ? ((NumberItem) localItem).getUnit() : null;
425 @SuppressWarnings("null")
426 List<HistoricItem> results = itemsFuture.get().stream().map(dynamoItem -> {
427 HistoricItem historicItem = dynamoItem.asHistoricItem(localItem, itemUnit);
428 if (historicItem == null) {
430 "Dynamo item {} serialized state '{}' cannot be converted to item {} {}. Item type changed since persistence. Ignoring",
431 dynamoItem.getClass().getSimpleName(), dynamoItem.getState(),
432 localItem.getClass().getSimpleName(), localItem.getName());
435 logger.trace("Dynamo item {} converted to historic item: {}", localItem, historicItem);
437 }).filter(value -> value != null).collect(Collectors.toList());
438 logger.debug("Query completed in {} ms. Filter was {}",
439 Duration.between(start, Instant.now()).toMillis(), filterDescription);
441 } catch (InterruptedException e) {
442 logger.warn("Query interrupted. Filter was {}", filterDescription);
443 return Collections.emptyList();
444 } catch (ExecutionException e) {
445 Throwable cause = e.getCause();
446 if (cause instanceof ResourceNotFoundException) {
447 logger.trace("Query failed since the DynamoDB table '{}' does not exist. Filter was {}", tableName,
449 } else if (logger.isTraceEnabled()) {
450 logger.trace("Query failed. Filter was {}", filterDescription, e);
452 logger.warn("Query failed {} {}. Filter was {}",
453 cause == null ? e.getClass().getSimpleName() : cause.getClass().getSimpleName(),
454 cause == null ? e.getMessage() : cause.getMessage(), filterDescription);
456 return Collections.emptyList();
458 } catch (Exception e) {
459 logger.error("Unexpected error with query having filter {}: {} {}. Returning empty query results.",
460 filterDescription, e.getClass().getSimpleName(), e.getMessage());
461 return Collections.emptyList();
466 * Retrieves the item for the given name from the item registry
469 * @return item with the given name, or null if no such item exists in item registry.
471 private @Nullable Item getItemFromRegistry(String itemName) {
473 return itemRegistry.getItem(itemName);
474 } catch (ItemNotFoundException e1) {
480 public List<PersistenceStrategy> getDefaultStrategies() {
481 return List.of(PersistenceStrategy.Globals.RESTORE, PersistenceStrategy.Globals.CHANGE);
485 public void store(Item item) {
490 public void store(Item item, @Nullable String alias) {
491 // Timestamp and capture state immediately as rest of the store is asynchronous (state might change in between)
492 ZonedDateTime time = ZonedDateTime.now();
494 logIfManyQueuedTasks();
495 if (!(item instanceof GenericItem)) {
498 if (item.getState() instanceof UnDefType) {
499 logger.debug("Undefined item state received. Not storing item {}.", item.getName());
502 if (!isReadyToStore()) {
503 logger.warn("Not ready to store (config error?), not storing item {}.", item.getName());
506 // Get Item describing the real type of data
507 // With non-group items this is same as the argument item. With Group items, this is item describing the type of
508 // state stored in the group.
509 final Item itemTemplate;
511 itemTemplate = getEffectiveItem(item);
512 } catch (IllegalStateException e) {
513 // Exception is raised when underlying item type cannot be determined with Group item
518 String effectiveName = (alias != null) ? alias : item.getName();
520 // We do not want to rely item.state since async context below can execute much later.
521 // We 'copy' the item for local use. copyItem also normalizes the unit with NumberItems.
522 final GenericItem copiedItem = copyItem(itemTemplate, item, effectiveName, null);
524 resolveTableSchema().thenAcceptAsync(resolved -> {
526 logger.warn("Table schema not resolved, not storing item {}.", copiedItem.getName());
530 DynamoDbEnhancedAsyncClient localClient = client;
531 DynamoDbAsyncClient localLowlevelClient = lowLevelClient;
532 DynamoDBConfig localConfig = dbConfig;
533 DynamoDBTableNameResolver localTableNameResolver = tableNameResolver;
534 if (!isProperlyConfigured || localClient == null || localLowlevelClient == null || localConfig == null
535 || localTableNameResolver == null) {
536 logger.warn("Not ready to store (config error?), not storing item {}.", item.getName());
540 Integer expireDays = localConfig.getExpireDays();
542 final DynamoDBItem<?> dto;
543 switch (localTableNameResolver.getTableSchema()) {
545 dto = AbstractDynamoDBItem.fromStateNew(copiedItem, time, expireDays);
548 dto = AbstractDynamoDBItem.fromStateLegacy(copiedItem, time);
551 throw new IllegalStateException("Unexpected. Bug");
553 logger.trace("store() called with item {} {} '{}', which was converted to DTO {}",
554 copiedItem.getClass().getSimpleName(), effectiveName, copiedItem.getState(), dto);
555 dto.accept(new DynamoDBItemVisitor<TableCreatingPutItem<? extends DynamoDBItem<?>>>() {
558 public TableCreatingPutItem<? extends DynamoDBItem<?>> visit(
559 DynamoDBBigDecimalItem dynamoBigDecimalItem) {
560 return new TableCreatingPutItem<DynamoDBBigDecimalItem>(DynamoDBPersistenceService.this,
561 dynamoBigDecimalItem, getTable(DynamoDBBigDecimalItem.class));
565 public TableCreatingPutItem<? extends DynamoDBItem<?>> visit(DynamoDBStringItem dynamoStringItem) {
566 return new TableCreatingPutItem<DynamoDBStringItem>(DynamoDBPersistenceService.this,
567 dynamoStringItem, getTable(DynamoDBStringItem.class));
570 }, executor).exceptionally(e -> {
571 logger.error("Unexcepted error", e);
576 private Item getEffectiveItem(Item item) {
577 final Item effectiveItem;
578 if (item instanceof GroupItem) {
579 Item baseItem = ((GroupItem) item).getBaseItem();
580 if (baseItem == null) {
581 // if GroupItem:<ItemType> is not defined in
582 // *.items using StringType
584 "Cannot detect ItemType for {} because the GroupItems' base type isn't set in *.items File.",
586 Iterator<Item> firstGroupMemberItem = ((GroupItem) item).getMembers().iterator();
587 if (firstGroupMemberItem.hasNext()) {
588 effectiveItem = firstGroupMemberItem.next();
590 throw new IllegalStateException("GroupItem " + item.getName()
591 + " does not have children nor base item set, cannot determine underlying item type. Aborting!");
594 effectiveItem = baseItem;
597 effectiveItem = item;
599 return effectiveItem;
603 * Copy item and optionally override name and state
605 * State is normalized to source item's unit with Quantity NumberItems and QuantityTypes
607 * @param itemTemplate 'template item' to be used to construct the new copy. It is also used to determine UoM unit
608 * and get GenericItem.type
609 * @param item item that is used to acquire name and state
610 * @param nameOverride name override for the resulting copy
611 * @param stateOverride state override for the resulting copy
612 * @throws IllegalArgumentException when state is QuantityType and not compatible with item
614 static GenericItem copyItem(Item itemTemplate, Item item, @Nullable String nameOverride,
615 @Nullable State stateOverride) {
616 final GenericItem copiedItem;
618 if (itemTemplate instanceof NumberItem) {
619 copiedItem = (GenericItem) itemTemplate.getClass().getDeclaredConstructor(String.class, String.class)
620 .newInstance(itemTemplate.getType(), nameOverride == null ? item.getName() : nameOverride);
622 copiedItem = (GenericItem) itemTemplate.getClass().getDeclaredConstructor(String.class)
623 .newInstance(nameOverride == null ? item.getName() : nameOverride);
626 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
627 | NoSuchMethodException | SecurityException e) {
628 throw new IllegalArgumentException(item.toString(), e);
630 State state = stateOverride == null ? item.getState() : stateOverride;
631 if (state instanceof QuantityType<?> && itemTemplate instanceof NumberItem) {
632 Unit<?> itemUnit = ((NumberItem) itemTemplate).getUnit();
633 if (itemUnit != null) {
634 State convertedState = ((QuantityType<?>) state).toUnit(itemUnit);
635 if (convertedState == null) {
636 logger.error("Unexpected unit conversion failure: {} to item unit {}", state, itemUnit);
637 throw new IllegalArgumentException(
638 String.format("Unexpected unit conversion failure: %s to item unit %s", state, itemUnit));
640 state = convertedState;
643 copiedItem.setState(state);
647 private void logIfManyQueuedTasks() {
648 if (executor instanceof ThreadPoolExecutor) {
649 ThreadPoolExecutor localExecutor = (ThreadPoolExecutor) executor;
650 if (localExecutor.getQueue().size() >= 5) {
651 logger.trace("executor queue size: {}, remaining space {}. Active threads {}",
652 localExecutor.getQueue().size(), localExecutor.getQueue().remainingCapacity(),
653 localExecutor.getActiveCount());
654 } else if (localExecutor.getQueue().size() >= 50) {
656 "Many ({}) tasks queued in executor! This might be sign of bad design or bug in the addon code.",
657 localExecutor.getQueue().size());
662 private String filterToString(FilterCriteria filter) {
663 return String.format(
664 "FilterCriteria@%s(item=%s, pageNumber=%d, pageSize=%d, time=[%s, %s, %s], state=[%s, %s of %s] )",
665 System.identityHashCode(filter), filter.getItemName(), filter.getPageNumber(), filter.getPageSize(),
666 filter.getBeginDate(), filter.getEndDate(), filter.getOrdering(), filter.getOperator(),
667 filter.getState(), filter.getState() == null ? "null" : filter.getState().getClass().getSimpleName());