Java 17 features (#15493)

- add missing @override
- Java style array syntax
- remove redundant modifiers
- always move String constants to left side in comparisons
- simplify lambda expressions and return statements
- use replace instead of replaceAll w/o regex

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich 2023-08-26 08:52:11 +02:00 committed by GitHub
parent d36833feef
commit 5b42c4b071
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 79 additions and 82 deletions

View File

@ -43,15 +43,18 @@ public class JSDependencyTracker extends AbstractScriptDependencyTracker {
} }
@Deactivate @Deactivate
@Override
public void deactivate() { public void deactivate() {
super.deactivate(); super.deactivate();
} }
@Override
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, unbind = "removeChangeTracker") @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, unbind = "removeChangeTracker")
public void addChangeTracker(ScriptDependencyTracker.Listener listener) { public void addChangeTracker(ScriptDependencyTracker.Listener listener) {
super.addChangeTracker(listener); super.addChangeTracker(listener);
} }
@Override
public void removeChangeTracker(ScriptDependencyTracker.Listener listener) { public void removeChangeTracker(ScriptDependencyTracker.Listener listener) {
super.removeChangeTracker(listener); super.removeChangeTracker(listener);
} }

View File

@ -57,10 +57,10 @@ public class HomekitCommandExtension extends AbstractConsoleCommandExtension {
private static final String PARAM_INSTANCE_HELP = " [--instance <instance id>]"; private static final String PARAM_INSTANCE_HELP = " [--instance <instance id>]";
private class CommandCompleter implements ConsoleCommandCompleter { private class CommandCompleter implements ConsoleCommandCompleter {
@Override
public boolean complete(String[] args, int cursorArgumentIndex, int cursorPosition, List<String> candidates) { public boolean complete(String[] args, int cursorArgumentIndex, int cursorPosition, List<String> candidates) {
if (cursorArgumentIndex == 0) { if (cursorArgumentIndex == 0) {
boolean result = SUBCMD_COMPLETER.complete(args, cursorArgumentIndex, cursorPosition, candidates); return SUBCMD_COMPLETER.complete(args, cursorArgumentIndex, cursorPosition, candidates);
return result;
} }
return false; return false;
} }

View File

@ -506,6 +506,7 @@ public class HomekitTaggedItem {
return id; return id;
} }
@Override
public String toString() { public String toString() {
return "Item:" + proxyItem.getItem() + " HomeKit type: '" + homekitAccessoryType.getTag() return "Item:" + proxyItem.getItem() + " HomeKit type: '" + homekitAccessoryType.getTag()
+ "' characteristic: '" + homekitCharacteristicType.getTag() + "'"; + "' characteristic: '" + homekitCharacteristicType.getTag() + "'";

View File

@ -437,7 +437,7 @@ public abstract class AbstractHomekitAccessoryImpl implements HomekitAccessory {
// Need to copy over everything except the current value, which we instead // Need to copy over everything except the current value, which we instead
// reach in and get the default value // reach in and get the default value
cJson.forEach((k, v) -> { cJson.forEach((k, v) -> {
if (k.equals("value")) { if ("value".equals(k)) {
Object defaultValue = ((BaseCharacteristic) c).getDefault(); Object defaultValue = ((BaseCharacteristic) c).getDefault();
if (defaultValue instanceof Boolean) { if (defaultValue instanceof Boolean) {
cBuilder.add("value", (boolean) defaultValue); cBuilder.add("value", (boolean) defaultValue);

View File

@ -98,7 +98,7 @@ public class BooleanItemReader {
} else if (state instanceof OpenClosedType) { } else if (state instanceof OpenClosedType) {
return state.equals(trueOpenClosedValue); return state.equals(trueOpenClosedValue);
} else if (state instanceof StringType) { } else if (state instanceof StringType) {
return state.toString().equalsIgnoreCase("Open") || state.toString().equalsIgnoreCase("Opened"); return "Open".equalsIgnoreCase(state.toString()) || "Opened".equalsIgnoreCase(state.toString());
} else if (localTrueThresheold != null) { } else if (localTrueThresheold != null) {
if (state instanceof DecimalType stateAsDecimalType) { if (state instanceof DecimalType stateAsDecimalType) {
final boolean result = stateAsDecimalType.toBigDecimal().compareTo(localTrueThresheold) > 0; final boolean result = stateAsDecimalType.toBigDecimal().compareTo(localTrueThresheold) > 0;

View File

@ -70,10 +70,10 @@ public class NeeoDirectoryResult {
this.totalMatchingItems = 1; this.totalMatchingItems = 1;
this.browseIdentifier = req.getBrowseIdentifier(); this.browseIdentifier = req.getBrowseIdentifier();
this.items = Arrays.stream(listItems).skip(this.offset).limit(this.limit).map(item -> { this.items = Arrays.stream(listItems).skip(this.offset).limit(this.limit)
return new NeeoDirectoryResultItem(item.getTitle(), item.getThumbNailUri(), null, item.getItemValue(), .map(item -> new NeeoDirectoryResultItem(item.getTitle(), item.getThumbNailUri(), null,
true); item.getItemValue(), true))
}).toArray(NeeoDirectoryResultItem[]::new); .toArray(NeeoDirectoryResultItem[]::new);
final NeeoDirectoryRequest current = new NeeoDirectoryRequest(this.offset, this.limit, this.browseIdentifier); final NeeoDirectoryRequest current = new NeeoDirectoryRequest(this.offset, this.limit, this.browseIdentifier);

View File

@ -104,7 +104,7 @@ public class NeeoDeviceChannelSerializer
} }
for (Class<? extends Command> cmd : item.getAcceptedCommandTypes()) { for (Class<? extends Command> cmd : item.getAcceptedCommandTypes()) {
if (!cmd.getSimpleName().equalsIgnoreCase("refreshtype")) { if (!"refreshtype".equalsIgnoreCase(cmd.getSimpleName())) {
commandTypes.add(cmd.getSimpleName().toLowerCase()); commandTypes.add(cmd.getSimpleName().toLowerCase());
} }
} }

View File

@ -68,9 +68,9 @@ public class BrainDashboardService extends DefaultServletService {
*/ */
@Override @Override
public boolean canHandleRoute(String[] paths) { public boolean canHandleRoute(String[] paths) {
return paths.length >= 1 && (paths[0].equalsIgnoreCase("brainstatus") || paths[0].equalsIgnoreCase("addbrain") return paths.length >= 1 && ("brainstatus".equalsIgnoreCase(paths[0]) || "addbrain".equalsIgnoreCase(paths[0])
|| paths[0].equalsIgnoreCase("removebrain") || paths[0].equalsIgnoreCase("getlog") || "removebrain".equalsIgnoreCase(paths[0]) || "getlog".equalsIgnoreCase(paths[0])
|| paths[0].equalsIgnoreCase("blinkled")); || "blinkled".equalsIgnoreCase(paths[0]));
} }
/** /**
@ -85,13 +85,13 @@ public class BrainDashboardService extends DefaultServletService {
Objects.requireNonNull(resp, "resp cannot be null"); Objects.requireNonNull(resp, "resp cannot be null");
try { try {
if (paths[0].equalsIgnoreCase("brainstatus")) { if ("brainstatus".equalsIgnoreCase(paths[0])) {
final List<BrainStatus> status = new ArrayList<>(); final List<BrainStatus> status = new ArrayList<>();
for (NeeoBrainServlet servlet : service.getServlets()) { for (NeeoBrainServlet servlet : service.getServlets()) {
status.add(servlet.getBrainStatus()); status.add(servlet.getBrainStatus());
} }
NeeoUtil.write(resp, gson.toJson(status)); NeeoUtil.write(resp, gson.toJson(status));
} else if (paths[0].equalsIgnoreCase("blinkled")) { } else if ("blinkled".equalsIgnoreCase(paths[0])) {
final String brainId = req.getParameter("brainid"); final String brainId = req.getParameter("brainid");
if (brainId == null) { if (brainId == null) {
NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID is null"))); NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID is null")));
@ -109,7 +109,7 @@ public class BrainDashboardService extends DefaultServletService {
} }
} }
} }
} else if (paths[0].equalsIgnoreCase("getlog")) { } else if ("getlog".equalsIgnoreCase(paths[0])) {
final String brainId = req.getParameter("brainid"); final String brainId = req.getParameter("brainid");
if (brainId == null) { if (brainId == null) {
NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID is null"))); NeeoUtil.write(resp, gson.toJson(new ReturnStatus("BrainID is null")));
@ -151,7 +151,7 @@ public class BrainDashboardService extends DefaultServletService {
} }
try { try {
if (paths[0].equalsIgnoreCase("removebrain")) { if ("removebrain".equalsIgnoreCase(paths[0])) {
final BrainInfo info = gson.fromJson(req.getReader(), BrainInfo.class); final BrainInfo info = gson.fromJson(req.getReader(), BrainInfo.class);
final String brainId = info.getBrainId(); final String brainId = info.getBrainId();
if (brainId == null) { if (brainId == null) {
@ -162,7 +162,7 @@ public class BrainDashboardService extends DefaultServletService {
NeeoUtil.write(resp, NeeoUtil.write(resp,
gson.toJson(new ReturnStatus("BrainID (" + brainId + ") could not be removed"))); gson.toJson(new ReturnStatus("BrainID (" + brainId + ") could not be removed")));
} }
} else if (paths[0].equalsIgnoreCase("addbrain")) { } else if ("addbrain".equalsIgnoreCase(paths[0])) {
final BrainInfo info = gson.fromJson(req.getReader(), BrainInfo.class); final BrainInfo info = gson.fromJson(req.getReader(), BrainInfo.class);
final String brainIp = info.getBrainIp(); final String brainIp = info.getBrainIp();
if (brainIp == null) { if (brainIp == null) {

View File

@ -84,7 +84,7 @@ public class NeeoBrainSearchService extends DefaultServletService {
*/ */
@Override @Override
public boolean canHandleRoute(String[] paths) { public boolean canHandleRoute(String[] paths) {
return paths.length >= 1 && paths[0].equalsIgnoreCase("db"); return paths.length >= 1 && "db".equalsIgnoreCase(paths[0]);
} }
/** /**
@ -107,12 +107,12 @@ public class NeeoBrainSearchService extends DefaultServletService {
final String path = paths[1].toLowerCase(); final String path = paths[1].toLowerCase();
if (path.equalsIgnoreCase("search")) { if ("search".equalsIgnoreCase(path)) {
String queryString = req.getQueryString(); String queryString = req.getQueryString();
if (queryString != null) { if (queryString != null) {
doSearch(queryString, resp); doSearch(queryString, resp);
} }
} else if (path.equalsIgnoreCase("adapterdefinition") && paths.length >= 3) { } else if ("adapterdefinition".equalsIgnoreCase(path) && paths.length >= 3) {
doAdapterDefinition(paths[2], resp); doAdapterDefinition(paths[2], resp);
} else { } else {
doQuery(path, resp); doQuery(path, resp);

View File

@ -141,7 +141,7 @@ public class NeeoBrainService extends DefaultServletService {
return false; return false;
} }
if (paths[0].equalsIgnoreCase("device")) { if ("device".equalsIgnoreCase(paths[0])) {
return true; return true;
} }
@ -158,7 +158,7 @@ public class NeeoBrainService extends DefaultServletService {
throw new IllegalArgumentException("paths cannot be empty"); throw new IllegalArgumentException("paths cannot be empty");
} }
final boolean hasDeviceStart = paths[0].equalsIgnoreCase("device"); final boolean hasDeviceStart = "device".equalsIgnoreCase(paths[0]);
if (hasDeviceStart) { if (hasDeviceStart) {
final PathInfo pathInfo = new PathInfo(paths); final PathInfo pathInfo = new PathInfo(paths);
@ -190,9 +190,9 @@ public class NeeoBrainService extends DefaultServletService {
// 4. Old subscribe path: /{thingUID}/subscribe or unsubscribe/{deviceid}/{devicekey} // 4. Old subscribe path: /{thingUID}/subscribe or unsubscribe/{deviceid}/{devicekey}
// 4. Old unsubscribe path: /{thingUID}/subscribe or unsubscribe/{deviceid} // 4. Old unsubscribe path: /{thingUID}/subscribe or unsubscribe/{deviceid}
final boolean hasDeviceStart = paths[0].equalsIgnoreCase("device"); final boolean hasDeviceStart = "device".equalsIgnoreCase(paths[0]);
if (hasDeviceStart && (paths.length >= 3 && !paths[2].equalsIgnoreCase("subscribe") if (hasDeviceStart && (paths.length >= 3 && !"subscribe".equalsIgnoreCase(paths[2])
&& !paths[2].equalsIgnoreCase("unsubscribe"))) { && !"unsubscribe".equalsIgnoreCase(paths[2]))) {
try { try {
final PathInfo pathInfo = new PathInfo(paths); final PathInfo pathInfo = new PathInfo(paths);

View File

@ -16,7 +16,9 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -51,6 +53,9 @@ public class ThingDashboardService extends DefaultServletService {
/** The logger */ /** The logger */
private final Logger logger = LoggerFactory.getLogger(ThingDashboardService.class); private final Logger logger = LoggerFactory.getLogger(ThingDashboardService.class);
private static final Set<String> STARTERS = Set.of("thingstatus", "getchannel", "getvirtualdevice", "restoredevice",
"refreshdevice", "deletedevice", "exportrules", "updatedevice");
/** The gson used for json manipulation */ /** The gson used for json manipulation */
private final Gson gson; private final Gson gson;
@ -83,14 +88,7 @@ public class ThingDashboardService extends DefaultServletService {
*/ */
@Override @Override
public boolean canHandleRoute(String[] paths) { public boolean canHandleRoute(String[] paths) {
return paths.length >= 1 && (paths[0].equalsIgnoreCase("thingstatus") // return paths.length >= 1 && STARTERS.contains(paths[0].toLowerCase(Locale.ROOT));
|| paths[0].equalsIgnoreCase("getchannel") //
|| paths[0].equalsIgnoreCase("getvirtualdevice") //
|| paths[0].equalsIgnoreCase("restoredevice") //
|| paths[0].equalsIgnoreCase("refreshdevice") //
|| paths[0].equalsIgnoreCase("deletedevice") //
|| paths[0].equalsIgnoreCase("exportrules") //
|| paths[0].equalsIgnoreCase("updatedevice"));
} }
/** /**
@ -105,10 +103,10 @@ public class ThingDashboardService extends DefaultServletService {
Objects.requireNonNull(resp, "resp cannot be null"); Objects.requireNonNull(resp, "resp cannot be null");
try { try {
if (paths[0].equalsIgnoreCase("thingstatus")) { if ("thingstatus".equalsIgnoreCase(paths[0])) {
final List<NeeoDevice> devices = context.getDefinitions().getAllDevices(); final List<NeeoDevice> devices = context.getDefinitions().getAllDevices();
NeeoUtil.write(resp, gson.toJson(devices)); NeeoUtil.write(resp, gson.toJson(devices));
} else if (paths[0].equalsIgnoreCase("getchannel")) { } else if ("getchannel".equalsIgnoreCase(paths[0])) {
final String itemName = NeeoUtil.decodeURIComponent(req.getParameter("itemname")); final String itemName = NeeoUtil.decodeURIComponent(req.getParameter("itemname"));
final List<NeeoDeviceChannel> channels = context.getDefinitions().getNeeoDeviceChannel(itemName); final List<NeeoDeviceChannel> channels = context.getDefinitions().getNeeoDeviceChannel(itemName);
if (channels == null) { if (channels == null) {
@ -116,7 +114,7 @@ public class ThingDashboardService extends DefaultServletService {
} else { } else {
NeeoUtil.write(resp, gson.toJson(new ReturnStatus(channels))); NeeoUtil.write(resp, gson.toJson(new ReturnStatus(channels)));
} }
} else if (paths[0].equalsIgnoreCase("getvirtualdevice")) { } else if ("getvirtualdevice".equalsIgnoreCase(paths[0])) {
final NeeoThingUID uid = context.generate(NeeoConstants.VIRTUAL_THING_TYPE); final NeeoThingUID uid = context.generate(NeeoConstants.VIRTUAL_THING_TYPE);
final NeeoDevice device = new NeeoDevice(uid, 0, NeeoDeviceType.EXCLUDE, "NEEO Integration", final NeeoDevice device = new NeeoDevice(uid, 0, NeeoDeviceType.EXCLUDE, "NEEO Integration",
"New Virtual Thing", new ArrayList<>(), null, null, null, null); "New Virtual Thing", new ArrayList<>(), null, null, null, null);
@ -145,7 +143,7 @@ public class ThingDashboardService extends DefaultServletService {
} }
try { try {
if (paths[0].equalsIgnoreCase("updatedevice")) { if ("updatedevice".equalsIgnoreCase(paths[0])) {
final NeeoDevice device = gson.fromJson(req.getReader(), NeeoDevice.class); final NeeoDevice device = gson.fromJson(req.getReader(), NeeoDevice.class);
context.getDefinitions().put(device); context.getDefinitions().put(device);
@ -154,7 +152,7 @@ public class ThingDashboardService extends DefaultServletService {
} }
NeeoUtil.write(resp, gson.toJson(ReturnStatus.SUCCESS)); NeeoUtil.write(resp, gson.toJson(ReturnStatus.SUCCESS));
} else if (paths[0].equalsIgnoreCase("restoredevice")) { } else if ("restoredevice".equalsIgnoreCase(paths[0])) {
final NeeoThingUID uid = new NeeoThingUID( final NeeoThingUID uid = new NeeoThingUID(
new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
context.getDefinitions().remove(uid); context.getDefinitions().remove(uid);
@ -164,7 +162,7 @@ public class ThingDashboardService extends DefaultServletService {
} else { } else {
NeeoUtil.write(resp, gson.toJson(new ReturnStatus(device))); NeeoUtil.write(resp, gson.toJson(new ReturnStatus(device)));
} }
} else if (paths[0].equalsIgnoreCase("refreshdevice")) { } else if ("refreshdevice".equalsIgnoreCase(paths[0])) {
final NeeoThingUID uid = new NeeoThingUID( final NeeoThingUID uid = new NeeoThingUID(
new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
final NeeoDevice device = context.getDefinitions().getDevice(uid); final NeeoDevice device = context.getDefinitions().getDevice(uid);
@ -173,13 +171,13 @@ public class ThingDashboardService extends DefaultServletService {
} else { } else {
NeeoUtil.write(resp, gson.toJson(new ReturnStatus(device))); NeeoUtil.write(resp, gson.toJson(new ReturnStatus(device)));
} }
} else if (paths[0].equalsIgnoreCase("deletedevice")) { } else if ("deletedevice".equalsIgnoreCase(paths[0])) {
final NeeoThingUID uid = new NeeoThingUID( final NeeoThingUID uid = new NeeoThingUID(
new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
final boolean deleted = context.getDefinitions().remove(uid); final boolean deleted = context.getDefinitions().remove(uid);
NeeoUtil.write(resp, gson.toJson(new ReturnStatus( NeeoUtil.write(resp, gson.toJson(new ReturnStatus(
deleted ? null : "Device " + uid + " was not found (possibly already deleted?)"))); deleted ? null : "Device " + uid + " was not found (possibly already deleted?)")));
} else if (paths[0].equalsIgnoreCase("exportrules")) { } else if ("exportrules".equalsIgnoreCase(paths[0])) {
final NeeoThingUID uid = new NeeoThingUID( final NeeoThingUID uid = new NeeoThingUID(
new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8)); new String(req.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
final NeeoDevice device = context.getDefinitions().getDevice(uid); final NeeoDevice device = context.getDefinitions().getDevice(uid);

View File

@ -540,7 +540,7 @@ public class CloudClient {
try { try {
headerValue = requestHeadersJson.getString(headerName); headerValue = requestHeadersJson.getString(headerName);
logger.debug("Jetty set header {} = {}", headerName, headerValue); logger.debug("Jetty set header {} = {}", headerName, headerValue);
if (!headerName.equalsIgnoreCase("Content-Length")) { if (!"Content-Length".equalsIgnoreCase(headerName)) {
request.header(headerName, headerValue); request.header(headerName, headerValue);
} }
} catch (JSONException e) { } catch (JSONException e) {

View File

@ -380,6 +380,6 @@ public class CloudService implements ActionService, CloudClientListener, EventSu
} }
private boolean supportsUpdates() { private boolean supportsUpdates() {
return cloudBaseUrl.indexOf(CFG_BASE_URL) >= 0; return cloudBaseUrl.contains(CFG_BASE_URL);
} }
} }

View File

@ -134,8 +134,8 @@ public abstract class AbstractDynamoDBItem<T> implements DynamoDBItem<T> {
ITEM_CLASS_MAP_NEW.put(PlayerItem.class, DynamoDBBigDecimalItem.class); // Different from LEGACY ITEM_CLASS_MAP_NEW.put(PlayerItem.class, DynamoDBBigDecimalItem.class); // Different from LEGACY
} }
public static final Class<? extends DynamoDBItem<?>> getDynamoItemClass(Class<? extends Item> itemClass, public static Class<? extends DynamoDBItem<?>> getDynamoItemClass(Class<? extends Item> itemClass, boolean legacy)
boolean legacy) throws NullPointerException { throws NullPointerException {
Class<? extends DynamoDBItem<?>> dtoclass = (legacy ? ITEM_CLASS_MAP_LEGACY : ITEM_CLASS_MAP_NEW) Class<? extends DynamoDBItem<?>> dtoclass = (legacy ? ITEM_CLASS_MAP_LEGACY : ITEM_CLASS_MAP_NEW)
.get(itemClass); .get(itemClass);
if (dtoclass == null) { if (dtoclass == null) {

View File

@ -287,9 +287,8 @@ public class DynamoDBPersistenceService implements QueryablePersistenceService {
String tableName = localTableNameResolver.fromClass(dtoClass); String tableName = localTableNameResolver.fromClass(dtoClass);
final TableSchema<T> schema = getDynamoDBTableSchema(dtoClass, expectedTableSchemaRevision); final TableSchema<T> schema = getDynamoDBTableSchema(dtoClass, expectedTableSchemaRevision);
@SuppressWarnings("unchecked") // OK since this is the only place tableCache is populated @SuppressWarnings("unchecked") // OK since this is the only place tableCache is populated
DynamoDbAsyncTable<T> table = (DynamoDbAsyncTable<T>) tableCache.computeIfAbsent(dtoClass, clz -> { DynamoDbAsyncTable<T> table = (DynamoDbAsyncTable<T>) tableCache.computeIfAbsent(dtoClass,
return localClient.table(tableName, schema); clz -> localClient.table(tableName, schema));
});
if (table == null) { if (table == null) {
// Invariant. To make null checker happy // Invariant. To make null checker happy
throw new IllegalStateException(); throw new IllegalStateException();

View File

@ -255,8 +255,7 @@ public class JdbcBaseDAO {
**************/ **************/
public @Nullable Integer doPingDB() throws JdbcSQLException { public @Nullable Integer doPingDB() throws JdbcSQLException {
try { try {
final @Nullable Integer result = Yank.queryScalar(sqlPingDB, Integer.class, null); return Yank.queryScalar(sqlPingDB, Integer.class, null);
return result;
} catch (YankSQLException e) { } catch (YankSQLException e) {
throw new JdbcSQLException(e); throw new JdbcSQLException(e);
} }
@ -264,8 +263,7 @@ public class JdbcBaseDAO {
public @Nullable String doGetDB() throws JdbcSQLException { public @Nullable String doGetDB() throws JdbcSQLException {
try { try {
final @Nullable String result = Yank.queryScalar(sqlGetDB, String.class, null); return Yank.queryScalar(sqlGetDB, String.class, null);
return result;
} catch (YankSQLException e) { } catch (YankSQLException e) {
throw new JdbcSQLException(e); throw new JdbcSQLException(e);
} }
@ -688,13 +686,13 @@ public class JdbcBaseDAO {
} else if (item instanceof ImageItem) { } else if (item instanceof ImageItem) {
return RawType.valueOf(objectAsString(v)); return RawType.valueOf(objectAsString(v));
} else if (item instanceof ContactItem || item instanceof PlayerItem || item instanceof SwitchItem) { } else if (item instanceof ContactItem || item instanceof PlayerItem || item instanceof SwitchItem) {
State state = TypeParser.parseState(item.getAcceptedDataTypes(), ((String) v).toString().trim()); State state = TypeParser.parseState(item.getAcceptedDataTypes(), ((String) v).trim());
if (state == null) { if (state == null) {
throw new UnsupportedOperationException("Unable to parse state for item " + item.toString()); throw new UnsupportedOperationException("Unable to parse state for item " + item.toString());
} }
return state; return state;
} else { } else {
State state = TypeParser.parseState(item.getAcceptedDataTypes(), ((String) v).toString()); State state = TypeParser.parseState(item.getAcceptedDataTypes(), ((String) v));
if (state == null) { if (state == null) {
throw new UnsupportedOperationException("Unable to parse state for item " + item.toString()); throw new UnsupportedOperationException("Unable to parse state for item " + item.toString());
} }
@ -731,7 +729,7 @@ public class JdbcBaseDAO {
if (v instanceof byte[]) { if (v instanceof byte[]) {
return new String((byte[]) v); return new String((byte[]) v);
} }
return ((String) v).toString(); return ((String) v);
} }
public String getItemType(Item i) { public String getItemType(Item i) {

View File

@ -41,7 +41,7 @@ public class StringUtilsExt {
* @param separators Array will be merged to str * @param separators Array will be merged to str
* @return * @return
*/ */
public static final String replaceArrayMerge(String str, String separate, Object[] separators) { public static String replaceArrayMerge(String str, String separate, Object[] separators) {
String s = str; String s = str;
for (int i = 0; i < separators.length; i++) { for (int i = 0; i < separators.length; i++) {
s = s.replaceFirst(separate, (String) separators[i]); s = s.replaceFirst(separate, (String) separators[i]);
@ -52,7 +52,7 @@ public class StringUtilsExt {
/** /**
* @see #replaceArrayMerge(String str, String separate, Object[] separators) * @see #replaceArrayMerge(String str, String separate, Object[] separators)
*/ */
public static final String replaceArrayMerge(String str, String[] separate, String[] separators) { public static String replaceArrayMerge(String str, String[] separate, String[] separators) {
String s = str; String s = str;
for (int i = 0; i < separators.length; i++) { for (int i = 0; i < separators.length; i++) {
s = s.replaceFirst(separate[i], separators[i]); s = s.replaceFirst(separate[i], separators[i]);
@ -115,7 +115,7 @@ public class StringUtilsExt {
// replace first ; with ? // replace first ; with ?
url = url.replaceFirst(";", "?"); url = url.replaceFirst(";", "?");
// replace other ; with & // replace other ; with &
url = url.replaceAll(";", "&"); url = url.replace(";", "&");
} }
if (url.split(":").length < 3 || url.indexOf("/") == -1) { if (url.split(":").length < 3 || url.indexOf("/") == -1) {

View File

@ -720,7 +720,7 @@ public class RRD4jPersistenceService implements QueryablePersistenceService {
} }
public void addArchives(String archivesString) { public void addArchives(String archivesString) {
String splitArchives[] = archivesString.split(":"); String[] splitArchives = archivesString.split(":");
for (String archiveString : splitArchives) { for (String archiveString : splitArchives) {
String[] opts = archiveString.split(","); String[] opts = archiveString.split(",");
if (opts.length != 4) { // check if correct number of parameters if (opts.length != 4) { // check if correct number of parameters

View File

@ -56,7 +56,7 @@ public class RegExTransformationService implements TransformationService {
String regex = substMatcher.group(1); String regex = substMatcher.group(1);
String substitution = substMatcher.group(2); String substitution = substMatcher.group(2);
String options = substMatcher.group(3); String options = substMatcher.group(3);
if (options.equals("g")) { if ("g".equals(options)) {
result = source.trim().replaceAll(regex, substitution); result = source.trim().replaceAll(regex, substitution);
} else { } else {
result = source.trim().replaceFirst(regex, substitution); result = source.trim().replaceFirst(regex, substitution);

View File

@ -211,8 +211,8 @@ public class ScaleTransformationService
final String value = properties.getProperty(entry); final String value = properties.getProperty(entry);
final Matcher matcher = LIMITS_PATTERN.matcher(entry); final Matcher matcher = LIMITS_PATTERN.matcher(entry);
if (matcher.matches() && (matcher.groupCount() == 4)) { if (matcher.matches() && (matcher.groupCount() == 4)) {
final boolean lowerInclusive = matcher.group(1).equals("["); final boolean lowerInclusive = "[".equals(matcher.group(1));
final boolean upperInclusive = matcher.group(4).equals("]"); final boolean upperInclusive = "]".equals(matcher.group(4));
final String lowLimit = matcher.group(2); final String lowLimit = matcher.group(2);
final String highLimit = matcher.group(3); final String highLimit = matcher.group(3);

View File

@ -465,7 +465,7 @@ public class ActionTemplateInterpreter implements HumanLanguageInterpreter {
String itemLabel = targetItem.getLabel(); String itemLabel = targetItem.getLabel();
String groupLabel = null; String groupLabel = null;
Item finalTargetItem = targetItem; Item finalTargetItem = targetItem;
if (finalTargetItem.getType().equals("Group") && memberTargets != null) { if ("Group".equals(finalTargetItem.getType()) && memberTargets != null) {
if (memberTargets.mergeState && memberTargets.itemName.isEmpty() && !memberTargets.itemType.isEmpty()) { if (memberTargets.mergeState && memberTargets.itemName.isEmpty() && !memberTargets.itemType.isEmpty()) {
// handle states that can be merged // handle states that can be merged
switch (memberTargets.itemType) { switch (memberTargets.itemType) {
@ -708,9 +708,9 @@ public class ActionTemplateInterpreter implements HumanLanguageInterpreter {
.filter(Objects::nonNull).toArray(String[]::new); .filter(Objects::nonNull).toArray(String[]::new);
itemOptionPlaceholder.posStaticValues = cmdDescription.getCommandOptions().stream() itemOptionPlaceholder.posStaticValues = cmdDescription.getCommandOptions().stream()
.collect(Collectors.toMap( .collect(Collectors.toMap(
option -> option.getLabel() != null ? option.getLabel().replaceAll(" ", "__") option -> option.getLabel() != null ? option.getLabel().replace(" ", "__")
: option.getCommand().replaceAll(" ", "__"), : option.getCommand().replace(" ", "__"),
option -> option.getCommand().replaceAll(" ", "__"))); option -> option.getCommand().replace(" ", "__")));
return itemOptionPlaceholder; return itemOptionPlaceholder;
} else if (stateDescription != null) { } else if (stateDescription != null) {
itemOptionPlaceholder.nerStaticValues = stateDescription.getOptions().stream() itemOptionPlaceholder.nerStaticValues = stateDescription.getOptions().stream()
@ -718,15 +718,15 @@ public class ActionTemplateInterpreter implements HumanLanguageInterpreter {
.filter(Objects::nonNull).toArray(String[]::new); .filter(Objects::nonNull).toArray(String[]::new);
if (isRead) { if (isRead) {
itemOptionPlaceholder.posStaticValues = stateDescription.getOptions().stream() itemOptionPlaceholder.posStaticValues = stateDescription.getOptions().stream()
.collect(Collectors.toMap(option -> option.getValue().replaceAll(" ", "__"), .collect(Collectors.toMap(option -> option.getValue().replace(" ", "__"),
option -> option.getLabel() != null ? option.getLabel().replaceAll(" ", "__") option -> option.getLabel() != null ? option.getLabel().replace(" ", "__")
: option.getValue().replaceAll(" ", "__"))); : option.getValue().replace(" ", "__")));
} else { } else {
itemOptionPlaceholder.posStaticValues = stateDescription.getOptions().stream() itemOptionPlaceholder.posStaticValues = stateDescription.getOptions().stream()
.collect(Collectors.toMap( .collect(Collectors.toMap(
option -> option.getLabel() != null ? option.getLabel().replaceAll(" ", "__") option -> option.getLabel() != null ? option.getLabel().replace(" ", "__")
: option.getValue().replaceAll(" ", "__"), : option.getValue().replace(" ", "__"),
option -> option.getValue().replaceAll(" ", "__"))); option -> option.getValue().replace(" ", "__")));
} }
return itemOptionPlaceholder; return itemOptionPlaceholder;
} }
@ -1022,7 +1022,7 @@ public class ActionTemplateInterpreter implements HumanLanguageInterpreter {
if (tag == null) { if (tag == null) {
return ""; return "";
} }
return tag.replaceAll("__", " "); return tag.replace("__", " ");
} }
private Map<String[], Item> getItemsByLabelTokensMap() { private Map<String[], Item> getItemsByLabelTokensMap() {

View File

@ -71,9 +71,8 @@ public class PicoTTSService extends AbstractCachedTTSService {
throw new TTSException("The passed voice is unsupported"); throw new TTSException("The passed voice is unsupported");
} }
boolean isAudioFormatSupported = this.audioFormats.stream().anyMatch(audioFormat -> { boolean isAudioFormatSupported = this.audioFormats.stream()
return audioFormat.isCompatible(requestedFormat); .anyMatch(audioFormat -> audioFormat.isCompatible(requestedFormat));
});
if (!isAudioFormatSupported) { if (!isAudioFormatSupported) {
throw new TTSException("The passed AudioFormat is unsupported"); throw new TTSException("The passed AudioFormat is unsupported");

View File

@ -166,8 +166,7 @@ public class PollyTTSService extends AbstractCachedTTSService {
throw new TTSException("Could not read from PollyTTS service"); throw new TTSException("Could not read from PollyTTS service");
} }
logger.debug("Audio Stream for '{}' in format {}", text, requestedFormat); logger.debug("Audio Stream for '{}' in format {}", text, requestedFormat);
AudioStream audioStream = new PollyTTSAudioStream(pollyAudioStream, requestedFormat); return new PollyTTSAudioStream(pollyAudioStream, requestedFormat);
return audioStream;
} catch (AmazonPollyException ex) { } catch (AmazonPollyException ex) {
throw new TTSException("Could not read from PollyTTS service: " + ex.getMessage(), ex); throw new TTSException("Could not read from PollyTTS service: " + ex.getMessage(), ex);
} }

View File

@ -126,7 +126,7 @@ public class PorcupineKSService implements KSService {
File localFile = new File(EXTRACTION_FOLDER, File localFile = new File(EXTRACTION_FOLDER,
relativePath.substring(relativePath.lastIndexOf(File.separator) + 1)); relativePath.substring(relativePath.lastIndexOf(File.separator) + 1));
if (!localFile.exists()) { if (!localFile.exists()) {
if (File.separator.equals("\\")) { if ("\\".equals(File.separator)) {
// bundle requires unix path separator // bundle requires unix path separator
logger.debug("use unix path separator"); logger.debug("use unix path separator");
relativePath = relativePath.replace("\\", "/"); relativePath = relativePath.replace("\\", "/");
@ -267,7 +267,7 @@ public class PorcupineKSService implements KSService {
"You can provide a specific model for fr language in {}, english language model will be used", "You can provide a specific model for fr language in {}, english language model will be used",
PORCUPINE_FOLDER); PORCUPINE_FOLDER);
} }
} else if (locale.getLanguage().equals("es")) { } else if ("es".equals(locale.getLanguage())) {
Path esPath = Path.of(PORCUPINE_FOLDER, "porcupine_params_es.pv"); Path esPath = Path.of(PORCUPINE_FOLDER, "porcupine_params_es.pv");
if (Files.exists(esPath)) { if (Files.exists(esPath)) {
modelPath = esPath.toString(); modelPath = esPath.toString();

View File

@ -46,7 +46,7 @@ public class CreateTTSCache {
usage(); usage();
return RC_USAGE; return RC_USAGE;
} }
if (!args[0].equalsIgnoreCase("--api-key")) { if (!"--api-key".equalsIgnoreCase(args[0])) {
usage(); usage();
return RC_API_KEY_MISSING; return RC_API_KEY_MISSING;
} }

View File

@ -95,7 +95,7 @@ public class VoskSTTService implements STTService {
try { try {
String osName = System.getProperty("os.name", "generic").toLowerCase(); String osName = System.getProperty("os.name", "generic").toLowerCase();
String osArch = System.getProperty("os.arch", "").toLowerCase(); String osArch = System.getProperty("os.arch", "").toLowerCase();
if (osName.contains("linux") && (osArch.equals("arm") || osArch.equals("armv7l"))) { if (osName.contains("linux") && ("arm".equals(osArch) || "armv7l".equals(osArch))) {
// workaround for loading required shared libraries // workaround for loading required shared libraries
loadSharedLibrariesArmv7l(); loadSharedLibrariesArmv7l();
} }