]> git.basschouten.com Git - openhab-addons.git/blob
869d789320d98eb6067851173409b99e8d235443
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.dynamodb.internal;
14
15 /**
16  * The DynamoDBTableNameResolver resolves DynamoDB table name for a given item.
17  *
18  * @author Sami Salonen - Initial contribution
19  *
20  */
21 public class DynamoDBTableNameResolver {
22
23     private final String tablePrefix;
24
25     public DynamoDBTableNameResolver(String tablePrefix) {
26         this.tablePrefix = tablePrefix;
27     }
28
29     public String fromItem(DynamoDBItem<?> item) {
30         final String[] tableName = new String[1];
31
32         // Use the visitor pattern to deduce the table name
33         item.accept(new DynamoDBItemVisitor() {
34
35             @Override
36             public void visit(DynamoDBBigDecimalItem dynamoBigDecimalItem) {
37                 tableName[0] = tablePrefix + "bigdecimal";
38             }
39
40             @Override
41             public void visit(DynamoDBStringItem dynamoStringItem) {
42                 tableName[0] = tablePrefix + "string";
43             }
44         });
45         return tableName[0];
46     }
47
48     /**
49      * Construct DynamoDBTableNameResolver corresponding to DynamoDBItem class
50      *
51      * @param clazz
52      * @return
53      */
54     public String fromClass(Class<? extends DynamoDBItem<?>> clazz) {
55         DynamoDBItem<?> dummy;
56         try {
57             // Construct new instance of this class (assuming presense no-argument constructor)
58             // in order to re-use fromItem(DynamoDBItem) constructor
59             dummy = clazz.getConstructor().newInstance();
60         } catch (Exception e) {
61             throw new IllegalStateException(String.format("Could not find suitable constructor for class %s", clazz));
62         }
63         return this.fromItem(dummy);
64     }
65 }