]> git.basschouten.com Git - openhab-addons.git/blob
c4d1f1fcd1478d3518b6ceeb4f4d563cdc1c51f9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.console;
14
15 import java.util.Arrays;
16 import java.util.Comparator;
17 import java.util.List;
18 import java.util.stream.Stream;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.io.console.Console;
23 import org.openhab.core.io.console.ConsoleCommandCompleter;
24 import org.openhab.core.io.console.StringsCompleter;
25 import org.openhab.core.io.console.extensions.AbstractConsoleCommandExtension;
26 import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
27 import org.openhab.core.persistence.PersistenceService;
28 import org.openhab.core.persistence.PersistenceServiceRegistry;
29 import org.openhab.persistence.jdbc.internal.ItemTableCheckEntry;
30 import org.openhab.persistence.jdbc.internal.ItemTableCheckEntryStatus;
31 import org.openhab.persistence.jdbc.internal.JdbcPersistenceService;
32 import org.openhab.persistence.jdbc.internal.JdbcPersistenceServiceConstants;
33 import org.openhab.persistence.jdbc.internal.exceptions.JdbcSQLException;
34 import org.osgi.service.component.annotations.Activate;
35 import org.osgi.service.component.annotations.Component;
36 import org.osgi.service.component.annotations.Reference;
37
38 /**
39  * The {@link JdbcCommandExtension} is responsible for handling console commands
40  *
41  * @author Jacob Laursen - Initial contribution
42  */
43 @NonNullByDefault
44 @Component(service = ConsoleCommandExtension.class)
45 public class JdbcCommandExtension extends AbstractConsoleCommandExtension implements ConsoleCommandCompleter {
46
47     private static final String CMD_TABLES = "tables";
48     private static final String SUBCMD_TABLES_LIST = "list";
49     private static final String SUBCMD_TABLES_CLEAN = "clean";
50     private static final String PARAMETER_ALL = "all";
51     private static final String PARAMETER_FORCE = "force";
52     private static final StringsCompleter CMD_COMPLETER = new StringsCompleter(List.of(CMD_TABLES), false);
53     private static final StringsCompleter SUBCMD_TABLES_COMPLETER = new StringsCompleter(
54             List.of(SUBCMD_TABLES_LIST, SUBCMD_TABLES_CLEAN), false);
55
56     private final PersistenceServiceRegistry persistenceServiceRegistry;
57
58     @Activate
59     public JdbcCommandExtension(final @Reference PersistenceServiceRegistry persistenceServiceRegistry) {
60         super(JdbcPersistenceServiceConstants.SERVICE_ID, "Interact with the JDBC persistence service.");
61         this.persistenceServiceRegistry = persistenceServiceRegistry;
62     }
63
64     @Override
65     public void execute(String[] args, Console console) {
66         if (args.length < 2 || args.length > 4 || !CMD_TABLES.equals(args[0])) {
67             printUsage(console);
68             return;
69         }
70         JdbcPersistenceService persistenceService = getPersistenceService();
71         if (persistenceService == null) {
72             return;
73         }
74         try {
75             if (!execute(persistenceService, args, console)) {
76                 printUsage(console);
77                 return;
78             }
79         } catch (JdbcSQLException e) {
80             console.println(e.toString());
81         }
82     }
83
84     private @Nullable JdbcPersistenceService getPersistenceService() {
85         for (PersistenceService persistenceService : persistenceServiceRegistry.getAll()) {
86             if (persistenceService instanceof JdbcPersistenceService) {
87                 return (JdbcPersistenceService) persistenceService;
88             }
89         }
90         return null;
91     }
92
93     private boolean execute(JdbcPersistenceService persistenceService, String[] args, Console console)
94             throws JdbcSQLException {
95         if (SUBCMD_TABLES_LIST.equalsIgnoreCase(args[1])) {
96             listTables(persistenceService, console, args.length == 3 && PARAMETER_ALL.equalsIgnoreCase(args[2]));
97             return true;
98         } else if (SUBCMD_TABLES_CLEAN.equalsIgnoreCase(args[1])) {
99             if (args.length == 3) {
100                 cleanupItem(persistenceService, console, args[2], false);
101                 return true;
102             } else if (args.length == 4 && PARAMETER_FORCE.equalsIgnoreCase(args[3])) {
103                 cleanupItem(persistenceService, console, args[2], true);
104                 return true;
105             } else {
106                 cleanupTables(persistenceService, console);
107                 return true;
108             }
109         }
110         return false;
111     }
112
113     private void listTables(JdbcPersistenceService persistenceService, Console console, Boolean all)
114             throws JdbcSQLException {
115         List<ItemTableCheckEntry> entries = persistenceService.getCheckedEntries();
116         if (!all) {
117             entries.removeIf(t -> t.getStatus() == ItemTableCheckEntryStatus.VALID);
118         }
119         entries.sort(Comparator.comparing(ItemTableCheckEntry::getTableName));
120         // FIXME: NoSuchElement when empty table - because of get()
121         int itemNameMaxLength = Math
122                 .max(entries.stream().map(t -> t.getItemName().length()).max(Integer::compare).get(), 4);
123         int tableNameMaxLength = Math
124                 .max(entries.stream().map(t -> t.getTableName().length()).max(Integer::compare).get(), 5);
125         int statusMaxLength = Stream.of(ItemTableCheckEntryStatus.values()).map(t -> t.toString().length())
126                 .max(Integer::compare).get();
127         console.println(String.format(
128                 "%1$-" + (tableNameMaxLength + 2) + "sRow Count  %2$-" + (itemNameMaxLength + 2) + "s%3$s", "Table",
129                 "Item", "Status"));
130         console.println("-".repeat(tableNameMaxLength) + "  " + "---------  " + "-".repeat(itemNameMaxLength) + "  "
131                 + "-".repeat(statusMaxLength));
132         for (ItemTableCheckEntry entry : entries) {
133             String tableName = entry.getTableName();
134             ItemTableCheckEntryStatus status = entry.getStatus();
135             long rowCount = status == ItemTableCheckEntryStatus.VALID
136                     || status == ItemTableCheckEntryStatus.ITEM_MISSING ? persistenceService.getRowCount(tableName) : 0;
137             console.println(String.format(
138                     "%1$-" + (tableNameMaxLength + 2) + "s%2$9d  %3$-" + (itemNameMaxLength + 2) + "s%4$s", tableName,
139                     rowCount, entry.getItemName(), status));
140         }
141     }
142
143     private void cleanupTables(JdbcPersistenceService persistenceService, Console console) throws JdbcSQLException {
144         console.println("Cleaning up all inconsistent items...");
145         List<ItemTableCheckEntry> entries = persistenceService.getCheckedEntries();
146         entries.removeIf(t -> t.getStatus() == ItemTableCheckEntryStatus.VALID || t.getItemName().isEmpty());
147         for (ItemTableCheckEntry entry : entries) {
148             console.print(entry.getItemName() + " -> ");
149             if (persistenceService.cleanupItem(entry)) {
150                 console.println("done.");
151             } else {
152                 console.println("skipped/failed.");
153             }
154         }
155     }
156
157     private void cleanupItem(JdbcPersistenceService persistenceService, Console console, String itemName, boolean force)
158             throws JdbcSQLException {
159         console.print("Cleaning up item " + itemName + "... ");
160         if (persistenceService.cleanupItem(itemName, force)) {
161             console.println("done.");
162         } else {
163             console.println("skipped/failed.");
164         }
165     }
166
167     @Override
168     public List<String> getUsages() {
169         return Arrays.asList(
170                 buildCommandUsage(CMD_TABLES + " " + SUBCMD_TABLES_LIST + " [" + PARAMETER_ALL + "]",
171                         "list tables (all = include valid)"),
172                 buildCommandUsage(
173                         CMD_TABLES + " " + SUBCMD_TABLES_CLEAN + " [<itemName>]" + " [" + PARAMETER_FORCE + "]",
174                         "clean inconsistent items (remove from index and drop tables)"));
175     }
176
177     @Override
178     public @Nullable ConsoleCommandCompleter getCompleter() {
179         return this;
180     }
181
182     @Override
183     public boolean complete(String[] args, int cursorArgumentIndex, int cursorPosition, List<String> candidates) {
184         if (cursorArgumentIndex <= 0) {
185             return CMD_COMPLETER.complete(args, cursorArgumentIndex, cursorPosition, candidates);
186         } else if (cursorArgumentIndex == 1) {
187             if (CMD_TABLES.equalsIgnoreCase(args[0])) {
188                 return SUBCMD_TABLES_COMPLETER.complete(args, cursorArgumentIndex, cursorPosition, candidates);
189             }
190         } else if (cursorArgumentIndex == 2) {
191             if (CMD_TABLES.equalsIgnoreCase(args[0])) {
192                 if (SUBCMD_TABLES_CLEAN.equalsIgnoreCase(args[1])) {
193                     JdbcPersistenceService persistenceService = getPersistenceService();
194                     if (persistenceService != null) {
195                         return new StringsCompleter(persistenceService.getItemNames(), true).complete(args,
196                                 cursorArgumentIndex, cursorPosition, candidates);
197                     }
198                 } else if (SUBCMD_TABLES_LIST.equalsIgnoreCase(args[1])) {
199                     new StringsCompleter(List.of(PARAMETER_ALL), false).complete(args, cursorArgumentIndex,
200                             cursorPosition, candidates);
201                 }
202             }
203         }
204         return false;
205     }
206 }