[hueemulation] Java 17 features (#15496)

- 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

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich 2023-08-25 17:48:55 +02:00 committed by GitHub
parent 17978b8625
commit d36833feef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 32 additions and 36 deletions

View File

@ -56,7 +56,7 @@ public class RuleUtils {
throw new IllegalStateException("Time pattern incorrect. Must be 'hh:mm[:ss]'. " + baseTime); throw new IllegalStateException("Time pattern incorrect. Must be 'hh:mm[:ss]'. " + baseTime);
} }
String randomizedTime[] = baseTime.split(":"); String[] randomizedTime = baseTime.split(":");
if (upperTime != null && !upperTime.isEmpty()) { if (upperTime != null && !upperTime.isEmpty()) {
String[] upperTimeParts = upperTime.split(":"); String[] upperTimeParts = upperTime.split(":");
@ -89,7 +89,7 @@ public class RuleUtils {
@SuppressWarnings({ "unused", "null" }) @SuppressWarnings({ "unused", "null" })
public static void validateHueHttpAddress(HueDataStore ds, String address) throws IllegalStateException { public static void validateHueHttpAddress(HueDataStore ds, String address) throws IllegalStateException {
String[] validation = address.split("/"); String[] validation = address.split("/");
if (validation.length < 6 || !validation[0].isEmpty() || !validation[1].equals("api")) { if (validation.length < 6 || !validation[0].isEmpty() || !"api".equals(validation[1])) {
throw new IllegalStateException("Given address invalid!"); throw new IllegalStateException("Given address invalid!");
} }
if ("groups".equals(validation[3]) && "action".equals(validation[5])) { if ("groups".equals(validation[3]) && "action".equals(validation[5])) {
@ -179,7 +179,7 @@ public class RuleUtils {
cronWeekdays.add(String.valueOf(c)); cronWeekdays.add(String.valueOf(c));
} }
} }
String hourMinSec[] = RuleUtils.computeRandomizedDayTime(time, randomize); String[] hourMinSec = RuleUtils.computeRandomizedDayTime(time, randomize);
// Cron expression: min hour day month weekdays // Cron expression: min hour day month weekdays
String cronExpression = hourMinSec[1] + " " + hourMinSec[0] + " * * " + String.join(",", cronWeekdays); String cronExpression = hourMinSec[1] + " " + hourMinSec[0] + " * * " + String.join(",", cronWeekdays);
@ -318,9 +318,9 @@ public class RuleUtils {
public static @Nullable String timeStringFromTrigger(List<Trigger> triggers) { public static @Nullable String timeStringFromTrigger(List<Trigger> triggers) {
Optional<Trigger> trigger; Optional<Trigger> trigger;
trigger = triggers.stream().filter(p -> p.getId().equals("crontrigger")).findFirst(); trigger = triggers.stream().filter(p -> "crontrigger".equals(p.getId())).findFirst();
if (trigger.isPresent()) { if (trigger.isPresent()) {
String cronParts[] = ((String) trigger.get().getConfiguration().get("cronExpression")).split(" "); String[] cronParts = ((String) trigger.get().getConfiguration().get("cronExpression")).split(" ");
if (cronParts.length != 5) { if (cronParts.length != 5) {
LOGGER.warn("Cron trigger has no valid cron expression: {}", String.join(",", cronParts)); LOGGER.warn("Cron trigger has no valid cron expression: {}", String.join(",", cronParts));
return null; return null;
@ -358,7 +358,7 @@ public class RuleUtils {
return String.format("W%d/T%s:%s:00", weekdays, cronParts[1], cronParts[0]); return String.format("W%d/T%s:%s:00", weekdays, cronParts[1], cronParts[0]);
} }
trigger = triggers.stream().filter(p -> p.getId().equals("timertrigger")).findFirst(); trigger = triggers.stream().filter(p -> "timertrigger".equals(p.getId())).findFirst();
if (trigger.isPresent()) { if (trigger.isPresent()) {
TimerConfig c = trigger.get().getConfiguration().as(TimerConfig.class); TimerConfig c = trigger.get().getConfiguration().as(TimerConfig.class);
if (c.repeat == null) { if (c.repeat == null) {
@ -370,7 +370,7 @@ public class RuleUtils {
c.randomizeTime); c.randomizeTime);
} }
} else { } else {
trigger = triggers.stream().filter(p -> p.getId().equals("absolutetrigger")).findFirst(); trigger = triggers.stream().filter(p -> "absolutetrigger".equals(p.getId())).findFirst();
if (trigger.isPresent()) { if (trigger.isPresent()) {
String date = (String) trigger.get().getConfiguration().get("date"); String date = (String) trigger.get().getConfiguration().get("date");
String time = (String) trigger.get().getConfiguration().get("time"); String time = (String) trigger.get().getConfiguration().get("time");

View File

@ -70,7 +70,7 @@ public class HueRuleConditionHandler extends BaseModuleHandler<Condition> implem
private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT); private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT);
private final Pattern timePattern = Pattern.compile("W(.*)/T(.*)/T(.*)"); private final Pattern timePattern = Pattern.compile("W(.*)/T(.*)/T(.*)");
// weekdays range from Monday to Sunday (1-7). The first entry is not used // weekdays range from Monday to Sunday (1-7). The first entry is not used
private final boolean weekDaysAllowed[] = { false, false, false, false, false, false, false, false }; private final boolean[] weekDaysAllowed = { false, false, false, false, false, false, false, false };
@SuppressWarnings({ "null", "unused" }) @SuppressWarnings({ "null", "unused" })
public HueRuleConditionHandler(Condition module, HueDataStore ds) { public HueRuleConditionHandler(Condition module, HueDataStore ds) {
@ -78,7 +78,7 @@ public class HueRuleConditionHandler extends BaseModuleHandler<Condition> implem
config = module.getConfiguration().as(HueRuleEntry.Condition.class); config = module.getConfiguration().as(HueRuleEntry.Condition.class);
// pattern: "/sensors/2/state/buttonevent" or "/config/localtime" // pattern: "/sensors/2/state/buttonevent" or "/config/localtime"
String validation[] = config.address.split("/"); String[] validation = config.address.split("/");
String uid = validation[2]; String uid = validation[2];
if ("groups".equals(validation[1]) && "action".equals(validation[3])) { if ("groups".equals(validation[1]) && "action".equals(validation[3])) {

View File

@ -22,7 +22,7 @@ public class AbstractHueState {
public boolean reachable = true; public boolean reachable = true;
public String mode = "homeautomation"; public String mode = "homeautomation";
public static enum AlertEnum { public enum AlertEnum {
none, none,
/** flashes light once */ /** flashes light once */
select, select,

View File

@ -91,8 +91,7 @@ public class HueAuthorizedConfig extends HueUnauthorizedConfig {
public JsonElement serialize(HueAuthorizedConfig src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(HueAuthorizedConfig src, Type typeOfSrc, JsonSerializationContext context) {
src.UTC = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); src.UTC = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
src.localtime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); src.localtime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
JsonElement jsonSubscription = context.serialize(src, HueAuthorizedConfigHelper.class); return context.serialize(src, HueAuthorizedConfigHelper.class);
return jsonSubscription;
} }
} }
} }

View File

@ -69,7 +69,7 @@ public class HueDataStore {
public String nextGroupID() { public String nextGroupID() {
int nextId = groups.size(); int nextId = groups.size();
while (true) { while (true) {
String id = "hueemulation" + String.valueOf(nextId); String id = "hueemulation" + nextId;
if (!groups.containsKey(id)) { if (!groups.containsKey(id)) {
return id; return id;
} }

View File

@ -35,7 +35,7 @@ import com.google.gson.annotations.SerializedName;
*/ */
@NonNullByDefault @NonNullByDefault
public class HueGroupEntry { public class HueGroupEntry {
public static enum TypeEnum { public enum TypeEnum {
LightGroup, // 1.4 LightGroup, // 1.4
Luminaire, // 1.4 Luminaire, // 1.4
LightSource, // 1.4 LightSource, // 1.4
@ -102,8 +102,7 @@ public class HueGroupEntry {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
JsonElement jsonSubscription = context.serialize(product, HueGroupHelper.class); return context.serialize(product, HueGroupHelper.class);
return jsonSubscription;
} }
} }
} }

View File

@ -176,8 +176,7 @@ public class HueLightEntry {
product.name = label; product.name = label;
} }
JsonElement jsonSubscription = context.serialize(product, HueDeviceHelper.class); return context.serialize(product, HueDeviceHelper.class);
return jsonSubscription;
} }
} }

View File

@ -41,7 +41,7 @@ public class HueRuleEntry {
public String owner = ""; public String owner = "";
public static enum Operator { public enum Operator {
unknown, unknown,
eq, // equals, Used for bool and int. eq, // equals, Used for bool and int.
gt, // greater than, Allowed on int values. gt, // greater than, Allowed on int values.

View File

@ -24,7 +24,7 @@ import org.eclipse.jdt.annotation.Nullable;
*/ */
@NonNullByDefault @NonNullByDefault
public class HueSceneEntry { public class HueSceneEntry {
public static enum TypeEnum { public enum TypeEnum {
LightScene, // 1.28 LightScene, // 1.28
GroupScene, // 1.28 GroupScene, // 1.28
} }

View File

@ -38,7 +38,7 @@ public class HueStateColorBulb extends HueStateBulb {
/** time for transition in centiseconds. */ /** time for transition in centiseconds. */
public int transitiontime; public int transitiontime;
public static enum ColorMode { public enum ColorMode {
ct, ct,
hs, hs,
xy xy

View File

@ -121,7 +121,7 @@ public class Rules implements RegistryChangeListener<Rule> {
entry.description = desc; entry.description = desc;
} }
rule.getConditions().stream().filter(c -> c.getTypeUID().equals("hue.ruleCondition")).forEach(c -> { rule.getConditions().stream().filter(c -> "hue.ruleCondition".equals(c.getTypeUID())).forEach(c -> {
HueRuleEntry.Condition condition = c.getConfiguration().as(HueRuleEntry.Condition.class); HueRuleEntry.Condition condition = c.getConfiguration().as(HueRuleEntry.Condition.class);
// address with pattern "/sensors/2/state/buttonevent" // address with pattern "/sensors/2/state/buttonevent"
String[] parts = condition.address.split("/"); String[] parts = condition.address.split("/");
@ -132,7 +132,7 @@ public class Rules implements RegistryChangeListener<Rule> {
entry.conditions.add(condition); entry.conditions.add(condition);
}); });
rule.getActions().stream().filter(a -> a.getTypeUID().equals("rules.HttpAction")).forEach(a -> { rule.getActions().stream().filter(a -> "rules.HttpAction".equals(a.getTypeUID())).forEach(a -> {
HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName()); HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName());
if (command == null) { if (command == null) {
return; return;
@ -205,11 +205,11 @@ public class Rules implements RegistryChangeListener<Rule> {
RuleBuilder builder, List<Trigger> oldTriggers, List<Condition> oldConditions, ItemRegistry itemRegistry) { RuleBuilder builder, List<Trigger> oldTriggers, List<Condition> oldConditions, ItemRegistry itemRegistry) {
// Preserve all triggers, conditions that are not part of hue rules // Preserve all triggers, conditions that are not part of hue rules
Map<String, Trigger> triggers = new TreeMap<>(); Map<String, Trigger> triggers = new TreeMap<>();
triggers.putAll(oldTriggers.stream().filter(a -> !a.getTypeUID().equals("core.ItemStateChangeTrigger")) triggers.putAll(oldTriggers.stream().filter(a -> !"core.ItemStateChangeTrigger".equals(a.getTypeUID()))
.collect(Collectors.toMap(e -> e.getId(), e -> e))); .collect(Collectors.toMap(e -> e.getId(), e -> e)));
Map<String, Condition> conditions = new TreeMap<>(); Map<String, Condition> conditions = new TreeMap<>();
conditions.putAll(oldConditions.stream().filter(a -> !a.getTypeUID().equals("hue.ruleCondition")) conditions.putAll(oldConditions.stream().filter(a -> !"hue.ruleCondition".equals(a.getTypeUID()))
.collect(Collectors.toMap(e -> e.getId(), e -> e))); .collect(Collectors.toMap(e -> e.getId(), e -> e)));
for (HueRuleEntry.Condition condition : hueConditions) { for (HueRuleEntry.Condition condition : hueConditions) {
@ -227,7 +227,7 @@ public class Rules implements RegistryChangeListener<Rule> {
String apikey) { String apikey) {
// Preserve all actions that are not "rules.HttpAction" // Preserve all actions that are not "rules.HttpAction"
List<Action> actions = new ArrayList<>(oldActions); List<Action> actions = new ArrayList<>(oldActions);
actions.removeIf(a -> a.getTypeUID().equals("rules.HttpAction")); actions.removeIf(a -> "rules.HttpAction".equals(a.getTypeUID()));
for (HueCommand command : hueActions) { for (HueCommand command : hueActions) {
command.address = "/api/" + apikey + command.address; command.address = "/api/" + apikey + command.address;

View File

@ -129,7 +129,7 @@ public class Scenes implements RegistryChangeListener<Rule> {
List<String> items = new ArrayList<>(); List<String> items = new ArrayList<>();
for (Action a : scene.getActions()) { for (Action a : scene.getActions()) {
if (!a.getTypeUID().equals("core.ItemCommandAction")) { if (!"core.ItemCommandAction".equals(a.getTypeUID())) {
continue; continue;
} }
ItemCommandActionConfig config = a.getConfiguration().as(ItemCommandActionConfig.class); ItemCommandActionConfig config = a.getConfiguration().as(ItemCommandActionConfig.class);

View File

@ -130,7 +130,7 @@ public class Schedules implements RegistryChangeListener<Rule> {
HueScheduleEntry entry = new HueScheduleEntry(); HueScheduleEntry entry = new HueScheduleEntry();
entry.name = rule.getName(); entry.name = rule.getName();
entry.description = rule.getDescription(); entry.description = rule.getDescription();
entry.autodelete = rule.getActions().stream().anyMatch(p -> p.getId().equals("autodelete")); entry.autodelete = rule.getActions().stream().anyMatch(p -> "autodelete".equals(p.getId()));
entry.status = ruleManager.isEnabled(rule.getUID()) ? "enabled" : "disabled"; entry.status = ruleManager.isEnabled(rule.getUID()) ? "enabled" : "disabled";
String timeStringFromTrigger = RuleUtils.timeStringFromTrigger(rule.getTriggers()); String timeStringFromTrigger = RuleUtils.timeStringFromTrigger(rule.getTriggers());
@ -142,7 +142,7 @@ public class Schedules implements RegistryChangeListener<Rule> {
entry.localtime = timeStringFromTrigger; entry.localtime = timeStringFromTrigger;
for (Action a : rule.getActions()) { for (Action a : rule.getActions()) {
if (!a.getTypeUID().equals("rules.HttpAction")) { if (!"rules.HttpAction".equals(a.getTypeUID())) {
continue; continue;
} }
HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName()); HueCommand command = RuleUtils.httpActionToHueCommand(cs.ds, a, rule.getName());
@ -208,7 +208,7 @@ public class Schedules implements RegistryChangeListener<Rule> {
if (command != null) { if (command != null) {
RuleUtils.validateHueHttpAddress(ds, command.address); RuleUtils.validateHueHttpAddress(ds, command.address);
actions.removeIf(a -> a.getId().equals("command")); // Remove old command action if any and add new one actions.removeIf(a -> "command".equals(a.getId())); // Remove old command action if any and add new one
actions.add(RuleUtils.createHttpAction(command, "command")); actions.add(RuleUtils.createHttpAction(command, "command"));
} else if (oldActions.isEmpty()) { // This is a new rule without an action yet } else if (oldActions.isEmpty()) { // This is a new rule without an action yet
throw new IllegalStateException("No command set!"); throw new IllegalStateException("No command set!");
@ -216,7 +216,7 @@ public class Schedules implements RegistryChangeListener<Rule> {
if (autodelete != null) { if (autodelete != null) {
// Remove action to remove rule after execution // Remove action to remove rule after execution
actions = actions.stream().filter(e -> !e.getId().equals("autodelete")) actions = actions.stream().filter(e -> !"autodelete".equals(e.getId()))
.collect(Collectors.toCollection(() -> new ArrayList<>())); .collect(Collectors.toCollection(() -> new ArrayList<>()));
if (autodelete) { // Add action to remove this rule again after execution if (autodelete) { // Add action to remove this rule again after execution
final Configuration actionConfig = new Configuration(); final Configuration actionConfig = new Configuration();

View File

@ -154,7 +154,7 @@ public class StatusResource implements RegistryListener {
+ user.getValue().name + "</b> <small>" + user.getValue().lastUseDate + "</small>") + user.getValue().name + "</b> <small>" + user.getValue().lastUseDate + "</small>")
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
String url = "http://" + cs.ds.config.ipaddress + ":" + String.valueOf(localDiscovery.getDefaultport()); String url = "http://" + cs.ds.config.ipaddress + ":" + localDiscovery.getDefaultport();
String reachable = localDiscovery.selfTests().stream() String reachable = localDiscovery.selfTests().stream()
.map(entry -> TR(TD(entry.address) + TD(toYesNo(entry.reachable)) + TD(toYesNo(entry.isOurs)))) .map(entry -> TR(TD(entry.address) + TD(toYesNo(entry.reachable)) + TD(toYesNo(entry.isOurs))))

View File

@ -120,7 +120,7 @@ public class UserManagement extends DefaultAbstractManagedProvider<HueUserAuthWi
return; return;
} }
logger.debug("APIKey {} added", apiKey); logger.debug("APIKey {} added", apiKey);
String l[] = label.split("#"); String[] l = label.split("#");
HueUserAuthWithSecrets hueUserAuth = new HueUserAuthWithSecrets(l[0], l.length == 2 ? l[1] : "openhab", apiKey, HueUserAuthWithSecrets hueUserAuth = new HueUserAuthWithSecrets(l[0], l.length == 2 ? l[1] : "openhab", apiKey,
clientKey); clientKey);
cs.ds.config.whitelist.put(apiKey, hueUserAuth); cs.ds.config.whitelist.put(apiKey, hueUserAuth);

View File

@ -349,9 +349,8 @@ public class UpnpServer extends HttpServlet implements Consumer<HueEmulationConf
} }
configChangeFuture = root.thenApply(this::createConfiguration) configChangeFuture = root.thenApply(this::createConfiguration)
.thenApplyAsync(this::performAddressTest, executor).thenApply(this::applyConfiguration) .thenApplyAsync(this::performAddressTest, executor).thenApply(this::applyConfiguration)
.thenCompose(c -> { .thenCompose(c -> c.startNow())
return c.startNow(); .whenComplete((HueEmulationConfigWithRuntime config, @Nullable Throwable e) -> {
}).whenComplete((HueEmulationConfigWithRuntime config, @Nullable Throwable e) -> {
if (e != null) { if (e != null) {
logger.warn("Upnp server: Address test failed", e); logger.warn("Upnp server: Address test failed", e);
} }