Some more code cleanup (#4021)

This cleanup includes:

* Use enhanced for loops
* Use text blocks
* Use Objects.equals
* Fix some typos
* Remove redundant variable initialization
* Remove redundant null checks with instanceof
* Remove redundant thrown Exceptions
* Remove redundant empty String concatenation

Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born 2024-02-04 11:17:55 +01:00 committed by GitHub
parent 2cca87a026
commit 85056d9d7b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
75 changed files with 250 additions and 294 deletions

View File

@ -16,10 +16,10 @@ import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -79,9 +79,7 @@ public class AddonInfoRegistry {
*/
public @Nullable AddonInfo getAddonInfo(String uid, @Nullable Locale locale) {
return addonInfoProviders.stream().map(p -> p.getAddonInfo(uid, locale)).filter(Objects::nonNull)
.collect(Collectors.groupingBy(a -> a == null ? "" : a.getUID(),
Collectors.collectingAndThen(Collectors.reducing(mergeAddonInfos), Optional::get)))
.get(uid);
.collect(Collectors.toMap(a -> a.getUID(), Function.identity(), mergeAddonInfos)).get(uid);
}
/**

View File

@ -161,7 +161,7 @@ public class AudioConsoleCommandExtension extends AbstractConsoleCommandExtensio
playOnSinks(args[0], args[1], null, console);
break;
case 3:
PercentType volume = null;
PercentType volume;
try {
volume = PercentType.valueOf(args[2]);
} catch (Exception e) {
@ -184,7 +184,7 @@ public class AudioConsoleCommandExtension extends AbstractConsoleCommandExtensio
playMelodyOnSinks(args[0], args[1], null, console);
break;
case 3:
PercentType volume = null;
PercentType volume;
try {
volume = PercentType.valueOf(args[2]);
} catch (Exception e) {

View File

@ -17,7 +17,6 @@ import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.Line.Info;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;
@ -77,10 +76,10 @@ public class AudioPlayer extends Thread {
logger.warn("No line found: {}", e.getMessage());
logger.info("Available lines are:");
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo(); // get available mixers
Mixer mixer = null;
for (int cnt = 0; cnt < mixerInfo.length; cnt++) {
mixer = AudioSystem.getMixer(mixerInfo[cnt]);
Line.Info[] lineInfos = mixer.getSourceLineInfo();
Mixer mixer;
for (Mixer.Info value : mixerInfo) {
mixer = AudioSystem.getMixer(value);
Info[] lineInfos = mixer.getSourceLineInfo();
for (Info lineInfo : lineInfos) {
logger.info("{}", lineInfo);
}

View File

@ -201,7 +201,7 @@ public class JavaSoundAudioSink extends AudioSinkAsync {
if (cachedVolume == null) {
Process p = Runtime.getRuntime()
.exec(new String[] { "osascript", "-e", "output volume of (get volume settings)" });
String value = null;
String value;
try (Scanner scanner = new Scanner(p.getInputStream(), StandardCharsets.UTF_8.name())) {
value = scanner.useDelimiter("\\A").next().strip();
}

View File

@ -69,8 +69,7 @@ public class ToneSynthesizer {
var melodySounds = new ArrayList<Tone>();
var noteTextList = melody.split("\\s");
var melodyTextIndex = 0;
for (var i = 0; i < noteTextList.length; i++) {
var noteText = noteTextList[i];
for (String noteText : noteTextList) {
var noteTextParts = noteText.split(":");
var soundMillis = 200;
switch (noteTextParts.length) {

View File

@ -132,7 +132,7 @@ public class SymmetricKeyCipher implements StorageCipher {
private SecretKey getOrGenerateEncryptionKey() throws NoSuchAlgorithmException, IOException {
Configuration configuration = configurationAdmin.getConfiguration(PID);
String encryptionKeyInBase64 = null;
String encryptionKeyInBase64;
Dictionary<String, Object> properties = configuration.getProperties();
if (properties == null) {
properties = new Hashtable<>();

View File

@ -71,7 +71,7 @@ public abstract class AbstractScriptModuleHandler<T extends Module> extends Base
private static String getValidConfigParameter(String parameter, Configuration config, String moduleId) {
Object value = config.get(parameter);
if (value != null && value instanceof String string && !string.trim().isEmpty()) {
if (value instanceof String string && !string.trim().isEmpty()) {
return string;
} else {
throw new IllegalStateException(String.format(

View File

@ -14,7 +14,6 @@ package org.openhab.core.automation.internal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@ -109,17 +108,15 @@ public class ConnectionValidator {
List<Input> inputs = type.getInputs(); // get inputs of the condition according to module type definition
// gets connected inputs from the condition module and put them into map
Set<Connection> cons = getConnections(action.getInputs());
Set<Connection> connections = getConnections(action.getInputs());
Map<String, Connection> connectionsMap = new HashMap<>();
Iterator<Connection> connectionsI = cons.iterator();
while (connectionsI.hasNext()) {
Connection connection = connectionsI.next();
for (Connection connection : connections) {
String inputName = connection.getInputName();
connectionsMap.put(inputName, connection);
}
// checks is there unconnected required inputs
if (inputs != null && !inputs.isEmpty()) {
if (!inputs.isEmpty()) {
for (Input input : inputs) {
String name = input.getName();
Connection connection = connectionsMap.get(name);
@ -185,17 +182,15 @@ public class ConnectionValidator {
List<Input> inputs = type.getInputs(); // get inputs of the condition according to module type definition
// gets connected inputs from the condition module and put them into map
Set<Connection> cons = getConnections(condition.getInputs());
Set<Connection> connections = getConnections(condition.getInputs());
Map<String, Connection> connectionsMap = new HashMap<>();
Iterator<Connection> connectionsI = cons.iterator();
while (connectionsI.hasNext()) {
Connection connection = connectionsI.next();
for (Connection connection : connections) {
String inputName = connection.getInputName();
connectionsMap.put(inputName, connection);
}
// checks is there unconnected required inputs
if (inputs != null && !inputs.isEmpty()) {
if (!inputs.isEmpty()) {
for (Input input : inputs) {
String name = input.getName();
Connection connection = connectionsMap.get(name);

View File

@ -708,7 +708,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
* @return the {@link ModuleHandlerFactory} responsible for the {@link ModuleType}.
*/
public @Nullable ModuleHandlerFactory getModuleHandlerFactory(String moduleTypeId) {
ModuleHandlerFactory mhf = null;
ModuleHandlerFactory mhf;
synchronized (this) {
mhf = moduleHandlerFactories.get(moduleTypeId);
}
@ -918,7 +918,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
private void removeMissingModuleTypes(Collection<String> moduleTypes) {
Map<String, List<String>> mapMissingHandlers = null;
for (String moduleTypeName : moduleTypes) {
Set<String> rules = null;
Set<String> rules;
synchronized (this) {
rules = mapModuleTypeToRules.get(moduleTypeName);
}
@ -1145,7 +1145,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
return true;
}
final String ruleUID = rule.getUID();
RuleStatus ruleStatus = null;
RuleStatus ruleStatus;
for (WrappedCondition wrappedCondition : conditions) {
ruleStatus = getRuleStatus(ruleUID);
if (ruleStatus != RuleStatus.RUNNING) {
@ -1173,7 +1173,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
if (actions.isEmpty()) {
return;
}
RuleStatus ruleStatus = null;
RuleStatus ruleStatus;
for (WrappedAction wrappedAction : actions) {
ruleStatus = getRuleStatus(ruleUID);
if (ruleStatus != RuleStatus.RUNNING) {

View File

@ -17,7 +17,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -537,9 +536,7 @@ public class RuleRegistryImpl extends AbstractRegistry<Rule, String, RuleProvide
private boolean isOptionalConfig(List<ConfigDescriptionParameter> configDescriptions) {
if (configDescriptions != null && !configDescriptions.isEmpty()) {
boolean required = false;
Iterator<ConfigDescriptionParameter> i = configDescriptions.iterator();
while (i.hasNext()) {
ConfigDescriptionParameter param = i.next();
for (ConfigDescriptionParameter param : configDescriptions) {
required = required || param.isRequired();
}
return !required;

View File

@ -15,7 +15,6 @@ package org.openhab.core.automation.internal.commands;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
@ -278,7 +277,7 @@ public class AutomationCommandList extends AutomationCommand {
private Collection<Rule> getRuleByFilter(Map<String, String> list) {
Collection<Rule> rules = new ArrayList<>();
if (!list.isEmpty()) {
Rule r = null;
Rule r;
String uid = list.get(id);
if (uid != null) {
r = autoCommands.getRule(uid);
@ -313,7 +312,7 @@ public class AutomationCommandList extends AutomationCommand {
*/
private Collection<RuleTemplate> getTemplateByFilter(Map<String, String> list) {
Collection<RuleTemplate> templates = new ArrayList<>();
RuleTemplate t = null;
RuleTemplate t;
String uid = list.get(id);
if (uid != null) {
t = autoCommands.getTemplate(uid, locale);
@ -348,7 +347,7 @@ public class AutomationCommandList extends AutomationCommand {
private Collection<ModuleType> getModuleTypeByFilter(Map<String, String> list) {
Collection<ModuleType> moduleTypes = new ArrayList<>();
if (!list.isEmpty()) {
ModuleType mt = null;
ModuleType mt;
String uid = list.get(id);
if (uid != null) {
mt = autoCommands.getModuleType(uid, locale);
@ -385,9 +384,7 @@ public class AutomationCommandList extends AutomationCommand {
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addCollection(Collection collection, Map list) {
if (collection != null && !collection.isEmpty()) {
Iterator i = collection.iterator();
while (i.hasNext()) {
Object element = i.next();
for (Object element : collection) {
if (element instanceof ModuleType type) {
list.put(type.getUID(), element);
}

View File

@ -156,7 +156,7 @@ public class CommandlineModuleTypeProvider extends AbstractCommandProvider<Modul
* @return the string <b>SUCCESS</b>.
*/
public String remove(URL url) {
List<String> portfolio = null;
List<String> portfolio;
synchronized (providerPortfolio) {
portfolio = providerPortfolio.remove(url);
}
@ -184,7 +184,7 @@ public class CommandlineModuleTypeProvider extends AbstractCommandProvider<Modul
throws ParsingException {
Set<ModuleType> providedObjects = parser.parse(inputStreamReader);
if (providedObjects != null && !providedObjects.isEmpty()) {
String uid = null;
String uid;
List<String> portfolio = new ArrayList<>();
synchronized (providerPortfolio) {
providerPortfolio.put(url, portfolio);

View File

@ -17,7 +17,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -119,9 +118,7 @@ public class CommandlineRuleImporter extends AbstractCommandProvider<Rule> {
throws ParsingException {
Set<Rule> providedRules = parser.parse(inputStreamReader);
if (providedRules != null && !providedRules.isEmpty()) {
Iterator<Rule> i = providedRules.iterator();
while (i.hasNext()) {
Rule rule = i.next();
for (Rule rule : providedRules) {
if (rule != null) {
if (ruleRegistry.get(rule.getUID()) != null) {
ruleRegistry.update(rule);

View File

@ -150,7 +150,7 @@ public class CommandlineTemplateProvider extends AbstractCommandProvider<RuleTem
* @return the string <b>SUCCESS</b>.
*/
public String remove(URL url) {
List<String> portfolio = null;
List<String> portfolio;
synchronized (providerPortfolio) {
portfolio = providerPortfolio.remove(url);
}

View File

@ -179,11 +179,7 @@ public class Utils {
if (count < 1) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(ch);
}
return sb.toString();
return String.valueOf(ch).repeat(count);
}
/**

View File

@ -88,7 +88,7 @@ public class CompositeTriggerHandler
ref = ref.substring(i + 1);
}
}
Object value = null;
Object value;
int idx = ReferenceResolver.getNextRefToken(ref, 1);
if (idx < ref.length()) {
String outputId = ref.substring(0, idx);

View File

@ -51,12 +51,11 @@ public class CompareConditionHandler extends BaseConditionModuleHandler {
@Override
public boolean isSatisfied(Map<String, @Nullable Object> context) {
Object operatorObj = this.module.getConfiguration().get(OPERATOR);
String operator = (operatorObj != null && operatorObj instanceof String s) ? s : null;
String operator = operatorObj instanceof String s ? s : null;
Object rightObj = this.module.getConfiguration().get(RIGHT_OP);
String rightOperandString = (rightObj != null && rightObj instanceof String s) ? s : null;
String rightOperandString = rightObj instanceof String s ? s : null;
Object leftObjFieldNameObj = this.module.getConfiguration().get(INPUT_LEFT_FIELD);
String leftObjectFieldName = (leftObjFieldNameObj != null && leftObjFieldNameObj instanceof String s) ? s
: null;
String leftObjectFieldName = leftObjFieldNameObj instanceof String s ? s : null;
if (rightOperandString == null || operator == null) {
return false;
} else {

View File

@ -266,7 +266,7 @@ public abstract class AbstractResourceBundleProvider<@NonNull E> {
if (!newPortfolio.contains(uid)) {
final @Nullable E removedObject = providedObjectsHolder.remove(uid);
if (removedObject != null) {
List<ProviderChangeListener<E>> snapshot = null;
List<ProviderChangeListener<E>> snapshot;
synchronized (listeners) {
snapshot = new LinkedList<>(listeners);
}
@ -333,7 +333,7 @@ public abstract class AbstractResourceBundleProvider<@NonNull E> {
for (String uid : portfolio) {
final @Nullable E removedObject = providedObjectsHolder.remove(uid);
if (removedObject != null) {
List<ProviderChangeListener<E>> snapshot = null;
List<ProviderChangeListener<E>> snapshot;
synchronized (listeners) {
snapshot = new LinkedList<>(listeners);
}
@ -431,7 +431,7 @@ public abstract class AbstractResourceBundleProvider<@NonNull E> {
@SuppressWarnings("unchecked")
protected void addNewProvidedObjects(List<String> newPortfolio, List<String> previousPortfolio,
Set<E> parsedObjects) {
List<ProviderChangeListener<E>> snapshot = null;
List<ProviderChangeListener<E>> snapshot;
synchronized (listeners) {
snapshot = new LinkedList<>(listeners);
}

View File

@ -13,7 +13,6 @@
package org.openhab.core.automation.internal.provider;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@ -94,7 +93,7 @@ public class AutomationResourceBundlesEventQueue<@NonNull E> implements Runnable
public void run() {
boolean waitForEvents = true;
while (true) {
List<BundleEvent> lQueue = null;
List<BundleEvent> lQueue;
synchronized (this) {
if (closed) {
notifyAll();
@ -117,9 +116,7 @@ public class AutomationResourceBundlesEventQueue<@NonNull E> implements Runnable
lQueue = queue;
shared = true;
}
Iterator<BundleEvent> events = lQueue.iterator();
while (events.hasNext()) {
BundleEvent event = events.next();
for (BundleEvent event : lQueue) {
try {
processBundleChanged(event);
synchronized (this) {

View File

@ -135,7 +135,7 @@ public class ModuleTypeI18nServiceImpl implements ModuleTypeI18nService {
@Nullable String llabel, @Nullable String ldescription) {
List<Input> inputs = moduleTypeI18nUtil.getLocalizedInputs(at.getInputs(), bundle, moduleTypeUID, locale);
List<Output> outputs = moduleTypeI18nUtil.getLocalizedOutputs(at.getOutputs(), bundle, moduleTypeUID, locale);
ActionType lat = null;
ActionType lat;
if (at instanceof CompositeActionType type) {
List<Action> modules = moduleI18nUtil.getLocalizedModules(type.getChildren(), bundle, moduleTypeUID,
ModuleTypeI18nUtil.MODULE_TYPE, locale);
@ -164,7 +164,7 @@ public class ModuleTypeI18nServiceImpl implements ModuleTypeI18nService {
@Nullable Locale locale, @Nullable List<ConfigDescriptionParameter> lconfigDescriptions,
@Nullable String llabel, @Nullable String ldescription) {
List<Input> inputs = moduleTypeI18nUtil.getLocalizedInputs(ct.getInputs(), bundle, moduleTypeUID, locale);
ConditionType lct = null;
ConditionType lct;
if (ct instanceof CompositeConditionType type) {
List<Condition> modules = moduleI18nUtil.getLocalizedModules(type.getChildren(), bundle, moduleTypeUID,
ModuleTypeI18nUtil.MODULE_TYPE, locale);
@ -193,7 +193,7 @@ public class ModuleTypeI18nServiceImpl implements ModuleTypeI18nService {
@Nullable Locale locale, @Nullable List<ConfigDescriptionParameter> lconfigDescriptions,
@Nullable String llabel, @Nullable String ldescription) {
List<Output> outputs = moduleTypeI18nUtil.getLocalizedOutputs(tt.getOutputs(), bundle, moduleTypeUID, locale);
TriggerType ltt = null;
TriggerType ltt;
if (tt instanceof CompositeTriggerType type) {
List<Trigger> modules = moduleI18nUtil.getLocalizedModules(type.getChildren(), bundle, moduleTypeUID,
ModuleTypeI18nUtil.MODULE_TYPE, locale);

View File

@ -65,7 +65,7 @@ public class ConfigDescriptionConverter extends GenericUnmarshaller<ConfigDescri
uriText = (String) context.get("config-description.uri");
}
URI uri = null;
URI uri;
if (uriText == null) {
throw new ConversionException("No URI provided");
}

View File

@ -93,7 +93,7 @@ public class ConfigDescriptionParameterConverter extends GenericUnmarshaller<Con
@Override
public @Nullable Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
ConfigDescriptionParameter configDescriptionParam = null;
ConfigDescriptionParameter configDescriptionParam;
// read attributes
Map<String, String> attributes = this.attributeMapValidator.readValidatedAttributes(reader);

View File

@ -62,7 +62,7 @@ public class ConverterValueMap {
throws ConversionException {
this.reader = reader;
this.context = context;
this.valueMap = readValueMap(this.reader, numberOfValues >= -1 ? numberOfValues : -1, this.context);
this.valueMap = readValueMap(this.reader, Math.max(numberOfValues, -1), this.context);
}
/**

View File

@ -19,7 +19,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@ -57,7 +56,7 @@ public class XmlDocumentReaderTest {
private @Nullable ConfigDescription readXML(String xml) throws IOException {
Path tempFile = Files.createTempFile(null, null);
tempFile.toFile().deleteOnExit();
Files.write(tempFile, xml.getBytes(StandardCharsets.UTF_8));
Files.writeString(tempFile, xml);
return new ConfigDescriptionReader().readFromXML(tempFile.toUri().toURL());
}

View File

@ -228,7 +228,7 @@ public class IpAddonFinder extends BaseAddonFinder {
String type = Objects.toString(parameters.get("type"), "");
String request = Objects.toString(parameters.get(PARAMETER_REQUEST), "");
String response = Objects.toString(matchProperties.get(MATCH_PROPERTY_RESPONSE), "");
int timeoutMs = 0;
int timeoutMs;
try {
timeoutMs = Integer.parseInt(Objects.toString(parameters.get(PARAMETER_TIMEOUT_MS)));
} catch (NumberFormatException e) {
@ -237,14 +237,14 @@ public class IpAddonFinder extends BaseAddonFinder {
continue;
}
@Nullable
InetAddress destIp = null;
InetAddress destIp;
try {
destIp = InetAddress.getByName(parameters.get(PARAMETER_DEST_IP));
} catch (UnknownHostException e) {
logger.warn("{}: discovery-parameter '{}' cannot be parsed", candidate.getUID(), PARAMETER_DEST_IP);
continue;
}
int destPort = 0;
int destPort;
try {
destPort = Integer.parseInt(Objects.toString(parameters.get(PARAMETER_DEST_PORT)));
} catch (NumberFormatException e) {

View File

@ -50,8 +50,8 @@ public class UsbSerialDeviceInformation {
public UsbSerialDeviceInformation(int vendorId, int productId, @Nullable String serialNumber,
@Nullable String manufacturer, @Nullable String product, int interfaceNumber,
@Nullable String interfaceDescription, String serialPort) {
this.vendorId = requireNonNull(vendorId);
this.productId = requireNonNull(productId);
this.vendorId = vendorId;
this.productId = productId;
this.serialNumber = serialNumber;
this.manufacturer = manufacturer;

View File

@ -56,6 +56,7 @@ public class DiscoveryResultBuilderTest {
discoveryResult = builder.build();
}
@Test
public void testInstance() {
assertThat(builder, is(instanceOf(DiscoveryResultBuilder.class)));
assertThat(builder.withLabel("TEST"), is(instanceOf(DiscoveryResultBuilder.class)));

View File

@ -13,7 +13,6 @@
package org.openhab.core.config.dispatch.internal;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
@ -190,7 +189,7 @@ public class ConfigDispatcher {
private void processOrphanExclusivePIDs() {
for (String orphanPID : exclusivePIDMap.getOrphanPIDs()) {
try {
Configuration configuration = null;
Configuration configuration;
if (orphanPID.contains(OpenHAB.SERVICE_CONTEXT_MARKER)) {
configuration = getConfigurationWithContext(orphanPID);
} else {
@ -276,7 +275,7 @@ public class ConfigDispatcher {
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void internalProcessConfigFile(File configFile) throws IOException, FileNotFoundException {
private void internalProcessConfigFile(File configFile) throws IOException {
if (configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
logger.debug("Ignoring file '{}'", configFile.getName());
return;

View File

@ -77,7 +77,7 @@ public class AuthorizePageServlet extends AbstractAuthPageServlet {
Map<String, String[]> params = req.getParameterMap();
try {
String message = "";
String message;
String scope = params.containsKey("scope") ? params.get("scope")[0] : "";
String clientId = params.containsKey("client_id") ? params.get("client_id")[0] : "";

View File

@ -232,7 +232,7 @@ public final class PEMTrustManager extends X509ExtendedTrustManager {
File certFile = new File(path);
if (certFile.exists()) {
try {
return new String(Files.readAllBytes(certFile.toPath()), StandardCharsets.UTF_8);
return Files.readString(certFile.toPath());
} catch (IOException e) {
LoggerFactory.getLogger(PEMTrustManager.class).error("An unexpected IOException occurred: ", e);
}

View File

@ -14,7 +14,6 @@ package org.openhab.core.io.rest.auth.internal;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@ -72,7 +71,7 @@ public class JwtHelper {
}
}
private RsaJsonWebKey generateNewKey() throws JoseException, FileNotFoundException, IOException {
private RsaJsonWebKey generateNewKey() throws JoseException, IOException {
RsaJsonWebKey newKey = RsaJwkGenerator.generateJwk(2048);
File file = new File(KEY_FILE_PATH);
@ -84,7 +83,7 @@ public class JwtHelper {
return newKey;
}
private RsaJsonWebKey loadOrGenerateKey() throws FileNotFoundException, JoseException, IOException {
private RsaJsonWebKey loadOrGenerateKey() throws JoseException, IOException {
try (final BufferedReader reader = Files.newBufferedReader(Paths.get(KEY_FILE_PATH))) {
return (RsaJsonWebKey) JsonWebKey.Factory.newJwk(reader.readLine());
} catch (IOException | JoseException e) {

View File

@ -116,7 +116,7 @@ public class InboxResource implements RESTResource {
ThingUID thingUIDObject = new ThingUID(thingUID);
String notEmptyLabel = label != null && !label.isEmpty() ? label : null;
String notEmptyNewThingId = newThingId != null && !newThingId.isEmpty() ? newThingId : null;
Thing thing = null;
Thing thing;
try {
thing = inbox.approve(thingUIDObject, notEmptyLabel, notEmptyNewThingId);
} catch (IllegalArgumentException e) {

View File

@ -99,7 +99,7 @@ public class MDNSAnnouncer {
private ServiceDescription getSSLServiceDescription() {
ServiceDescription description = getDefaultServiceDescription();
description.serviceType = "_" + mdnsName + "-server-ssl._tcp.local.";
description.serviceName = "" + mdnsName + "-ssl";
description.serviceName = mdnsName + "-ssl";
description.servicePort = httpSSLPort;
return description;
}

View File

@ -177,7 +177,7 @@ public class SitemapSubscriptionService implements ModelRepositoryChangeListener
creationInstants.remove(subscriptionId);
callbacks.remove(subscriptionId);
String sitemapPage = pageOfSubscription.remove(subscriptionId);
if (sitemapPage != null && !pageOfSubscription.values().contains(sitemapPage)) {
if (sitemapPage != null && !pageOfSubscription.containsValue(sitemapPage)) {
// this was the only subscription listening on this page, so we can dispose the listener
ListenerRecord listener = pageChangeListeners.remove(sitemapPage);
if (listener != null) {

View File

@ -94,7 +94,7 @@ public class ProxyFilter implements ContainerRequestFilter {
// it
String uriString = scheme + "://" + host.trim();
URI newBaseUri = null;
URI newBaseUri;
try {
newBaseUri = new URI(uriString);
} catch (URISyntaxException e) {

View File

@ -73,9 +73,7 @@ public class BitUtilitiesExtractIndividualMethodsTest {
for (int offset = 0; offset < 5; offset++) {
int byteIndex = origByteIndex + offset;
byte[] bytesOffsetted = new byte[origBytes.length + offset];
for (int i = 0; i < bytesOffsetted.length; i++) {
bytesOffsetted[i] = 99;
}
Arrays.fill(bytesOffsetted, (byte) 99);
System.arraycopy(origBytes, 0, bytesOffsetted, offset, origBytes.length);
// offsetted:
streamBuilder.add(new Object[] { expectedResult, type, bytesOffsetted, byteIndex });

View File

@ -44,7 +44,7 @@ public class JavaCommPortProvider implements SerialPortProvider {
@Override
public @Nullable SerialPortIdentifier getPortIdentifier(URI port) {
CommPortIdentifier ident = null;
CommPortIdentifier ident;
try {
ident = CommPortIdentifier.getPortIdentifier(port.getPath());
} catch (javax.comm.NoSuchPortException e) {

View File

@ -107,7 +107,7 @@ public class SerialPortUtil {
static @Nullable String initSerialPort(String port, @Nullable String serialPortsProperty) {
String pathSeparator = File.pathSeparator;
Set<String> serialPorts = null;
Set<String> serialPorts;
if (serialPortsProperty != null) {
serialPorts = Stream.of(serialPortsProperty.split(pathSeparator)).collect(Collectors.toSet());
} else {

View File

@ -385,7 +385,7 @@ public class UpnpIOServiceImpl implements UpnpIOService, RegistryListener {
}
private Service findService(Device device, String serviceID) {
Service service = null;
Service service;
String namespace = device.getType().getNamespace();
if (UDAServiceId.DEFAULT_NAMESPACE.equals(namespace)
|| UDAServiceId.BROKEN_DEFAULT_NAMESPACE.equals(namespace)) {

View File

@ -98,7 +98,7 @@ public class ModelRepositoryImpl implements ModelRepository {
public boolean addOrRefreshModel(String name, final InputStream originalInputStream) {
logger.info("Loading model '{}'", name);
Resource resource = null;
byte[] bytes = null;
byte[] bytes;
try (InputStream inputStream = originalInputStream) {
bytes = inputStream.readAllBytes();
String validationResult = validateModel(name, new ByteArrayInputStream(bytes));

View File

@ -323,7 +323,7 @@ public class Voice {
}
if (locale != null) {
String[] split = locale.split("-");
Locale loc = null;
Locale loc;
if (split.length == 2) {
loc = new Locale(split[0], split[1]);
} else {
@ -450,7 +450,7 @@ public class Voice {
dialogContextBuilder.withListeningItem(listeningItem);
}
if (locale != null) {
Locale loc = null;
Locale loc;
String[] split = locale.split("-");
if (split.length == 2) {
loc = new Locale(split[0], split[1]);

View File

@ -178,7 +178,7 @@ public class NumberExtensions {
if (type instanceof QuantityType qtype && x instanceof QuantityType qx) {
return operator_equals(qtype, qx);
}
if (type != null && type instanceof DecimalType decimalType && x != null) {
if (type instanceof DecimalType decimalType && x != null) {
return decimalType.toBigDecimal().compareTo(numberToBigDecimal(x)) == 0;
} else {
return type == x; // both might be null, then we should return true
@ -189,7 +189,7 @@ public class NumberExtensions {
if (type instanceof QuantityType qtype && x instanceof QuantityType qx) {
return operator_notEquals(qtype, qx);
}
if (type != null && type instanceof DecimalType decimalType && x != null) {
if (type instanceof DecimalType decimalType && x != null) {
return decimalType.toBigDecimal().compareTo(numberToBigDecimal(x)) != 0;
} else {
return type != x; // both might be null, then we should return
@ -201,7 +201,7 @@ public class NumberExtensions {
if (type instanceof QuantityType qtype && x instanceof QuantityType qx) {
return operator_greaterThan(qtype, qx);
}
if (type != null && type instanceof DecimalType decimalType && x != null) {
if (type instanceof DecimalType decimalType && x != null) {
return decimalType.toBigDecimal().compareTo(numberToBigDecimal(x)) > 0;
} else {
return false;
@ -212,7 +212,7 @@ public class NumberExtensions {
if (type instanceof QuantityType qtype && x instanceof QuantityType qx) {
return operator_greaterEqualsThan(qtype, qx);
}
if (type != null && type instanceof DecimalType decimalType && x != null) {
if (type instanceof DecimalType decimalType && x != null) {
return decimalType.toBigDecimal().compareTo(numberToBigDecimal(x)) >= 0;
} else {
return false;
@ -223,7 +223,7 @@ public class NumberExtensions {
if (type instanceof QuantityType qtype && x instanceof QuantityType qx) {
return operator_lessThan(qtype, qx);
}
if (type != null && type instanceof DecimalType decimalType && x != null) {
if (type instanceof DecimalType decimalType && x != null) {
return decimalType.toBigDecimal().compareTo(numberToBigDecimal(x)) < 0;
} else {
return false;
@ -234,7 +234,7 @@ public class NumberExtensions {
if (type instanceof QuantityType qtype && x instanceof QuantityType qx) {
return operator_lessEqualsThan(qtype, qx);
}
if (type != null && type instanceof DecimalType decimalType && x != null) {
if (type instanceof DecimalType decimalType && x != null) {
return decimalType.toBigDecimal().compareTo(numberToBigDecimal(x)) <= 0;
} else {
return false;

View File

@ -80,7 +80,7 @@ public class GenericItemChannelLinkProvider extends AbstractProvider<ItemChannel
private void createItemChannelLink(String context, String itemName, String channelUID, Configuration configuration)
throws BindingConfigParseException {
ChannelUID channelUIDObject = null;
ChannelUID channelUIDObject;
try {
channelUIDObject = new ChannelUID(channelUID);
} catch (IllegalArgumentException e) {

View File

@ -54,7 +54,7 @@ public class ThingFactory {
*/
public static ThingUID generateRandomThingUID(ThingTypeUID thingTypeUID) {
String uuid = UUID.randomUUID().toString();
String thingId = uuid.substring(uuid.length() - 12, uuid.length());
String thingId = uuid.substring(uuid.length() - 12);
return new ThingUID(thingTypeUID, thingId);
}

View File

@ -228,7 +228,7 @@ public class CommunicationManager implements EventSubscriber, RegistryChangeList
private @Nullable ProfileTypeUID determineProfileTypeUID(ItemChannelLink link, Item item, @Nullable Thing thing) {
ProfileTypeUID profileTypeUID = getConfiguredProfileTypeUID(link);
Channel channel = null;
Channel channel;
if (profileTypeUID == null) {
if (thing == null) {
return null;

View File

@ -189,7 +189,7 @@ public final class FirmwareImpl implements Firmware {
digestString.append(String.format("%02x", b));
}
if (!md5Hash.equals(digestString.toString())) {
if (!md5Hash.contentEquals(digestString)) {
bytes = null;
throw new IllegalStateException(
String.format("Invalid MD5 checksum. Expected %s, but was %s.", md5Hash, digestString));

View File

@ -118,7 +118,7 @@ public class TimestampOffsetProfile implements StateProfile {
}
Duration finalOffset = towardsItem ? offset : offset.negated();
Type result = UnDefType.UNDEF;
Type result;
if (type instanceof DateTimeType timeType) {
ZonedDateTime zdt = timeType.getZonedDateTime();

View File

@ -80,10 +80,9 @@ public class ThingTypeConverter extends AbstractDescriptionTypeConverter<ThingTy
@SuppressWarnings("unchecked")
protected List<ChannelXmlResult>[] getChannelTypeReferenceObjects(NodeIterator nodeIterator)
throws ConversionException {
List<ChannelXmlResult> channelTypeReferences = null;
List<ChannelXmlResult> channelGroupTypeReferences = null;
channelTypeReferences = (List<ChannelXmlResult>) nodeIterator.nextList("channels", false);
List<ChannelXmlResult> channelTypeReferences = (List<ChannelXmlResult>) nodeIterator.nextList("channels",
false);
if (channelTypeReferences == null) {
channelGroupTypeReferences = (List<ChannelXmlResult>) nodeIterator.nextList("channel-groups", false);
}

View File

@ -66,7 +66,7 @@ public class IconServletTest {
}
public String getOutput() {
return new String(outputStream.toByteArray());
return outputStream.toString();
}
public void reset() {

View File

@ -15,7 +15,6 @@ package org.openhab.core.ui.internal.proxy;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@ -29,7 +28,6 @@ import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -91,13 +89,8 @@ public class BlockingProxyServlet extends HttpServlet {
// wait for the response headers to arrive or the timeout to expire
Response httpResponse = listener.get(TIMEOUT, TimeUnit.MILLISECONDS);
// get response headers
HttpFields headers = httpResponse.getHeaders();
Iterator<HttpField> iterator = headers.iterator();
// copy all headers
while (iterator.hasNext()) {
HttpField header = iterator.next();
// copy all response headers
for (HttpField header : httpResponse.getHeaders()) {
response.setHeader(header.getName(), header.getValue());
}
} catch (TimeoutException e) {

View File

@ -243,7 +243,7 @@ public class ProxyServletService extends HttpServlet {
String.format("Widget '%s' could not be found!", widgetId));
}
String uriString = null;
String uriString;
if (widget instanceof Image image) {
uriString = image.getUrl();
} else if (widget instanceof Video video) {

View File

@ -241,7 +241,7 @@ public class ItemUIRegistryImplTest {
String testLabel = "Label [%.3f " + UnitUtils.UNIT_PLACEHOLDER + "]";
when(widgetMock.getLabel()).thenReturn(testLabel);
when(itemMock.getState()).thenReturn(new QuantityType<>("" + 10f / 3f + " °C"));
when(itemMock.getState()).thenReturn(new QuantityType<>(10f / 3f + " °C"));
String label = uiRegistry.getLabel(widgetMock);
assertEquals("Label [3" + SEP + "333 °C]", label);
}
@ -261,7 +261,7 @@ public class ItemUIRegistryImplTest {
String testLabel = "Label [%.0f " + UnitUtils.UNIT_PLACEHOLDER + "]";
when(widgetMock.getLabel()).thenReturn(testLabel);
when(itemMock.getState()).thenReturn(new QuantityType<>("" + 10f / 3f + " °C"));
when(itemMock.getState()).thenReturn(new QuantityType<>(10f / 3f + " °C"));
String label = uiRegistry.getLabel(widgetMock);
assertEquals("Label [3 °C]", label);
}
@ -271,7 +271,7 @@ public class ItemUIRegistryImplTest {
String testLabel = "Label [%d %%]";
when(widgetMock.getLabel()).thenReturn(testLabel);
when(itemMock.getState()).thenReturn(new QuantityType<>("" + 10f / 3f + " %"));
when(itemMock.getState()).thenReturn(new QuantityType<>(10f / 3f + " %"));
String label = uiRegistry.getLabel(widgetMock);
assertEquals("Label [3 %]", label);
}
@ -281,7 +281,7 @@ public class ItemUIRegistryImplTest {
String testLabel = "Label [%.0f %%]";
when(widgetMock.getLabel()).thenReturn(testLabel);
when(itemMock.getState()).thenReturn(new QuantityType<>("" + 10f / 3f + " %"));
when(itemMock.getState()).thenReturn(new QuantityType<>(10f / 3f + " %"));
String label = uiRegistry.getLabel(widgetMock);
assertEquals("Label [3 %]", label);
}
@ -301,7 +301,7 @@ public class ItemUIRegistryImplTest {
String testLabel = "Label [%d " + UnitUtils.UNIT_PLACEHOLDER + "]";
when(widgetMock.getLabel()).thenReturn(testLabel);
when(itemMock.getState()).thenReturn(new QuantityType<>("" + 10f / 3f + " %"));
when(itemMock.getState()).thenReturn(new QuantityType<>(10f / 3f + " %"));
String label = uiRegistry.getLabel(widgetMock);
assertEquals("Label [3 %]", label);
}
@ -311,7 +311,7 @@ public class ItemUIRegistryImplTest {
String testLabel = "Label [%.0f " + UnitUtils.UNIT_PLACEHOLDER + "]";
when(widgetMock.getLabel()).thenReturn(testLabel);
when(itemMock.getState()).thenReturn(new QuantityType<>("" + 10f / 3f + " %"));
when(itemMock.getState()).thenReturn(new QuantityType<>(10f / 3f + " %"));
String label = uiRegistry.getLabel(widgetMock);
assertEquals("Label [3 %]", label);
}
@ -743,11 +743,11 @@ public class ItemUIRegistryImplTest {
when(widgetMock.getLabel()).thenReturn(testLabel);
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("21");
when(conditon.getCondition()).thenReturn("<");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("21");
when(condition.getCondition()).thenReturn("<");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(condition);
ColorArray rule = mock(ColorArray.class);
when(rule.getConditions()).thenReturn(conditions);
when(rule.getArg()).thenReturn("yellow");
@ -772,11 +772,11 @@ public class ItemUIRegistryImplTest {
when(widgetMock.getLabel()).thenReturn(testLabel);
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("20");
when(conditon.getCondition()).thenReturn("==");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("20");
when(condition.getCondition()).thenReturn("==");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(condition);
ColorArray rule = mock(ColorArray.class);
when(rule.getConditions()).thenReturn(conditions);
when(rule.getArg()).thenReturn("yellow");
@ -950,29 +950,29 @@ public class ItemUIRegistryImplTest {
when(widgetMock.getLabel()).thenReturn(testLabel);
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("18");
when(conditon.getCondition()).thenReturn(">=");
Condition conditon2 = mock(Condition.class);
when(conditon2.getState()).thenReturn("21");
when(conditon2.getCondition()).thenReturn("<");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("18");
when(condition.getCondition()).thenReturn(">=");
Condition condition2 = mock(Condition.class);
when(condition2.getState()).thenReturn("21");
when(condition2.getCondition()).thenReturn("<");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(conditon2);
conditions.add(condition);
conditions.add(condition2);
ColorArray rule = mock(ColorArray.class);
when(rule.getConditions()).thenReturn(conditions);
when(rule.getArg()).thenReturn("yellow");
BasicEList<ColorArray> rules = new BasicEList<>();
rules.add(rule);
Condition conditon3 = mock(Condition.class);
when(conditon3.getState()).thenReturn("21");
when(conditon3.getCondition()).thenReturn(">=");
Condition conditon4 = mock(Condition.class);
when(conditon4.getState()).thenReturn("24");
when(conditon4.getCondition()).thenReturn("<");
Condition condition3 = mock(Condition.class);
when(condition3.getState()).thenReturn("21");
when(condition3.getCondition()).thenReturn(">=");
Condition condition4 = mock(Condition.class);
when(condition4.getState()).thenReturn("24");
when(condition4.getCondition()).thenReturn("<");
BasicEList<Condition> conditions2 = new BasicEList<>();
conditions2.add(conditon3);
conditions2.add(conditon4);
conditions2.add(condition3);
conditions2.add(condition4);
ColorArray rule2 = mock(ColorArray.class);
when(rule2.getConditions()).thenReturn(conditions2);
when(rule2.getArg()).thenReturn("red");
@ -1004,8 +1004,6 @@ public class ItemUIRegistryImplTest {
color = uiRegistry.getLabelColor(widgetMock);
assertEquals("blue", color);
conditions5 = null;
when(itemMock.getState()).thenReturn(new DecimalType(24.0));
color = uiRegistry.getLabelColor(widgetMock);
@ -1019,29 +1017,29 @@ public class ItemUIRegistryImplTest {
@Test
public void getValueColor() {
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("18");
when(conditon.getCondition()).thenReturn(">=");
Condition conditon2 = mock(Condition.class);
when(conditon2.getState()).thenReturn("21");
when(conditon2.getCondition()).thenReturn("<");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("18");
when(condition.getCondition()).thenReturn(">=");
Condition condition2 = mock(Condition.class);
when(condition2.getState()).thenReturn("21");
when(condition2.getCondition()).thenReturn("<");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(conditon2);
conditions.add(condition);
conditions.add(condition2);
ColorArray rule = mock(ColorArray.class);
when(rule.getConditions()).thenReturn(conditions);
when(rule.getArg()).thenReturn("yellow");
BasicEList<ColorArray> rules = new BasicEList<>();
rules.add(rule);
Condition conditon3 = mock(Condition.class);
when(conditon3.getState()).thenReturn("21");
when(conditon3.getCondition()).thenReturn(">=");
Condition conditon4 = mock(Condition.class);
when(conditon4.getState()).thenReturn("24");
when(conditon4.getCondition()).thenReturn("<");
Condition condition3 = mock(Condition.class);
when(condition3.getState()).thenReturn("21");
when(condition3.getCondition()).thenReturn(">=");
Condition condition4 = mock(Condition.class);
when(condition4.getState()).thenReturn("24");
when(condition4.getCondition()).thenReturn("<");
BasicEList<Condition> conditions2 = new BasicEList<>();
conditions2.add(conditon3);
conditions2.add(conditon4);
conditions2.add(condition3);
conditions2.add(condition4);
ColorArray rule2 = mock(ColorArray.class);
when(rule2.getConditions()).thenReturn(conditions2);
when(rule2.getArg()).thenReturn("red");
@ -1073,8 +1071,6 @@ public class ItemUIRegistryImplTest {
color = uiRegistry.getValueColor(widgetMock);
assertEquals("blue", color);
conditions5 = null;
when(itemMock.getState()).thenReturn(new DecimalType(24.0));
color = uiRegistry.getValueColor(widgetMock);
@ -1088,29 +1084,29 @@ public class ItemUIRegistryImplTest {
@Test
public void getIconColor() {
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("18");
when(conditon.getCondition()).thenReturn(">=");
Condition conditon2 = mock(Condition.class);
when(conditon2.getState()).thenReturn("21");
when(conditon2.getCondition()).thenReturn("<");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("18");
when(condition.getCondition()).thenReturn(">=");
Condition condition2 = mock(Condition.class);
when(condition2.getState()).thenReturn("21");
when(condition2.getCondition()).thenReturn("<");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(conditon2);
conditions.add(condition);
conditions.add(condition2);
ColorArray rule = mock(ColorArray.class);
when(rule.getConditions()).thenReturn(conditions);
when(rule.getArg()).thenReturn("yellow");
BasicEList<ColorArray> rules = new BasicEList<>();
rules.add(rule);
Condition conditon3 = mock(Condition.class);
when(conditon3.getState()).thenReturn("21");
when(conditon3.getCondition()).thenReturn(">=");
Condition conditon4 = mock(Condition.class);
when(conditon4.getState()).thenReturn("24");
when(conditon4.getCondition()).thenReturn("<");
Condition condition3 = mock(Condition.class);
when(condition3.getState()).thenReturn("21");
when(condition3.getCondition()).thenReturn(">=");
Condition condition4 = mock(Condition.class);
when(condition4.getState()).thenReturn("24");
when(condition4.getCondition()).thenReturn("<");
BasicEList<Condition> conditions2 = new BasicEList<>();
conditions2.add(conditon3);
conditions2.add(conditon4);
conditions2.add(condition3);
conditions2.add(condition4);
ColorArray rule2 = mock(ColorArray.class);
when(rule2.getConditions()).thenReturn(conditions2);
when(rule2.getArg()).thenReturn("red");
@ -1142,8 +1138,6 @@ public class ItemUIRegistryImplTest {
color = uiRegistry.getIconColor(widgetMock);
assertEquals("blue", color);
conditions5 = null;
when(itemMock.getState()).thenReturn(new DecimalType(24.0));
color = uiRegistry.getIconColor(widgetMock);
@ -1157,15 +1151,15 @@ public class ItemUIRegistryImplTest {
@Test
public void getVisibility() {
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("21");
when(conditon.getCondition()).thenReturn(">=");
Condition conditon2 = mock(Condition.class);
when(conditon2.getState()).thenReturn("24");
when(conditon2.getCondition()).thenReturn("<");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("21");
when(condition.getCondition()).thenReturn(">=");
Condition condition2 = mock(Condition.class);
when(condition2.getState()).thenReturn("24");
when(condition2.getCondition()).thenReturn("<");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(conditon2);
conditions.add(condition);
conditions.add(condition2);
VisibilityRule rule = mock(VisibilityRule.class);
when(rule.getConditions()).thenReturn(conditions);
BasicEList<VisibilityRule> rules = new BasicEList<>();
@ -1211,15 +1205,15 @@ public class ItemUIRegistryImplTest {
when(widgetMock.eClass()).thenReturn(textEClass);
when(widgetMock.getIcon()).thenReturn(null);
when(widgetMock.getStaticIcon()).thenReturn(null);
Condition conditon = mock(Condition.class);
when(conditon.getState()).thenReturn("21");
when(conditon.getCondition()).thenReturn(">=");
Condition conditon2 = mock(Condition.class);
when(conditon2.getState()).thenReturn("24");
when(conditon2.getCondition()).thenReturn("<");
Condition condition = mock(Condition.class);
when(condition.getState()).thenReturn("21");
when(condition.getCondition()).thenReturn(">=");
Condition condition2 = mock(Condition.class);
when(condition2.getState()).thenReturn("24");
when(condition2.getCondition()).thenReturn("<");
BasicEList<Condition> conditions = new BasicEList<>();
conditions.add(conditon);
conditions.add(conditon2);
conditions.add(condition);
conditions.add(condition2);
IconRule rule = mock(IconRule.class);
when(rule.getConditions()).thenReturn(conditions);
when(rule.getArg()).thenReturn("temperature");

View File

@ -856,7 +856,7 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
if (!isForced && newState.equals(oldState)) {
String template = language.getString(STATE_ALREADY_SINGULAR);
String cmdName = "state_" + command.toString().toLowerCase();
String stateText = null;
String stateText;
try {
stateText = language.getString(cmdName);
} catch (Exception e) {

View File

@ -21,10 +21,10 @@ import java.util.List;
*/
public class TokenList {
private List<String> list = null;
private List<String> list;
private int head = 0;
private int tail = 0;
private int head;
private int tail;
/**
* Constructs a new instance.

View File

@ -71,7 +71,7 @@ public class ItemUpdater extends AbstractItemEventSubscriber {
} catch (ReflectiveOperationException e) {
// Should never happen
logger.warn("{} while creating {} instance: {}", e.getClass().getSimpleName(),
state.getClass().getSimpleName(), e.getMessage());
state.getSimpleName(), e.getMessage());
}
}
}

View File

@ -15,6 +15,7 @@ package org.openhab.core.internal.types;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -226,12 +227,9 @@ public class StateDescriptionFragmentImpl implements StateDescriptionFragment {
return false;
}
StateDescriptionFragmentImpl other = (StateDescriptionFragmentImpl) obj;
return (minimum != null ? minimum.equals(other.minimum) : other.minimum == null)
&& (maximum != null ? maximum.equals(other.maximum) : other.maximum == null)
&& (step != null ? step.equals(other.step) : other.step == null)
&& (pattern != null ? pattern.equals(other.pattern) : other.pattern == null)
&& (readOnly != null ? readOnly.equals(other.readOnly) : other.readOnly == null)
&& (options != null ? options.equals(other.options) : other.options == null);
return Objects.equals(minimum, other.minimum) && Objects.equals(maximum, other.maximum)
&& Objects.equals(step, other.step) && Objects.equals(pattern, other.pattern)
&& Objects.equals(readOnly, other.readOnly) && Objects.equals(options, other.options);
}
@Override

View File

@ -186,7 +186,7 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
String itemName = entry.getKey();
PersistedItem persistedItem = entry.getValue();
Item item = itemFactory.createItem(persistedItem.itemType, itemName);
if (item != null && item instanceof GenericItem genericItem) {
if (item instanceof GenericItem genericItem) {
iterator.remove();
configureItem(persistedItem, genericItem);
notifyListenersAboutAddedElement(item);
@ -217,7 +217,7 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
@Override
protected @Nullable Item toElement(String itemName, PersistedItem persistedItem) {
Item item = null;
Item item;
if (GroupItem.TYPE.equals(persistedItem.itemType)) {
String baseItemType = persistedItem.baseItemType;
@ -236,7 +236,7 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
item = createItem(persistedItem.itemType, itemName);
}
if (item != null && item instanceof GenericItem genericItem) {
if (item instanceof GenericItem genericItem) {
configureItem(persistedItem, genericItem);
}

View File

@ -199,7 +199,7 @@ public class ItemEventFactory extends AbstractEventFactory {
}
private static <T> T parseType(String typeName, String valueToParse, Class<T> desiredClass) {
Object parsedObject = null;
Object parsedObject;
String simpleClassName = typeName + TYPE_POSTFIX;
parsedObject = parseSimpleClassName(simpleClassName, valueToParse);

View File

@ -77,7 +77,7 @@ public class DateTimeType implements PrimitiveType, State, Command {
}
public DateTimeType(String zonedValue) {
ZonedDateTime date = null;
ZonedDateTime date;
try {
// direct parsing (date and time)
try {
@ -228,7 +228,7 @@ public class DateTimeType implements PrimitiveType, State, Command {
}
private ZonedDateTime parse(String value) throws DateTimeParseException {
ZonedDateTime date = null;
ZonedDateTime date;
try {
date = ZonedDateTime.parse(value, PARSER_TZ_RFC);
} catch (DateTimeParseException tzMsRfcException) {

View File

@ -223,15 +223,15 @@ public class PointType implements ComplexType, Command, State {
private void canonicalize(DecimalType aLat, DecimalType aLon) {
latitude = FLAT.add(aLat.toBigDecimal()).remainder(CIRCLE);
longitude = aLon.toBigDecimal();
if (latitude.compareTo(BigDecimal.ZERO) == -1) {
if (latitude.compareTo(BigDecimal.ZERO) < 0) {
latitude = latitude.add(CIRCLE);
}
latitude = latitude.subtract(FLAT);
if (latitude.compareTo(RIGHT) == 1) {
if (latitude.compareTo(RIGHT) > 0) {
latitude = FLAT.subtract(latitude);
longitude = longitude.add(FLAT);
} else if (latitude.compareTo(RIGHT.negate()) == -1) {
} else if (latitude.compareTo(RIGHT.negate()) < 0) {
latitude = FLAT.negate().subtract(latitude);
longitude = longitude.add(FLAT);
}

View File

@ -76,7 +76,7 @@ public class HttpServiceUtil {
}
value = ref.getProperty(Constants.SERVICE_RANKING);
final int serviceRanking;
if (value == null || !(value instanceof Integer)) {
if (!(value instanceof Integer)) {
serviceRanking = 0;
} else {
serviceRanking = (Integer) value;

View File

@ -12,6 +12,8 @@
*/
package org.openhab.core.types;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -84,7 +86,7 @@ public class CommandOption {
return false;
}
CommandOption other = (CommandOption) obj;
return command.equals(other.command) && (label != null ? label.equals(other.label) : other.label == null);
return command.equals(other.command) && Objects.equals(label, other.label);
}
@Override

View File

@ -15,6 +15,7 @@ package org.openhab.core.types;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -136,10 +137,8 @@ public class StateDescription {
return false;
}
StateDescription other = (StateDescription) obj;
return (minimum != null ? minimum.equals(other.minimum) : other.minimum == null)
&& (maximum != null ? maximum.equals(other.maximum) : other.maximum == null)
&& (step != null ? step.equals(other.step) : other.step == null)
&& (pattern != null ? pattern.equals(other.pattern) : other.pattern == null)
return Objects.equals(minimum, other.minimum) && Objects.equals(maximum, other.maximum)
&& Objects.equals(step, other.step) && Objects.equals(pattern, other.pattern)
&& readOnly == other.readOnly //
&& options.equals(other.options);
}

View File

@ -12,6 +12,8 @@
*/
package org.openhab.core.types;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -76,7 +78,7 @@ public final class StateOption {
return false;
}
StateOption other = (StateOption) obj;
return value.equals(other.value) && (label != null ? label.equals(other.label) : other.label == null);
return value.equals(other.value) && Objects.equals(label, other.label);
}
@Override

View File

@ -105,9 +105,9 @@ public class ColorUtil {
* @return array of three {@link PercentType} with the RGB values in the range 0 to 100 percent.
*/
public static PercentType[] hsbToRgbPercent(HSBType hsb) {
PercentType red = null;
PercentType green = null;
PercentType blue = null;
PercentType red;
PercentType green;
PercentType blue;
final BigDecimal h = hsb.getHue().toBigDecimal().divide(BIG_DECIMAL_100, 10, RoundingMode.HALF_UP);
final BigDecimal s = hsb.getSaturation().toBigDecimal().divide(BIG_DECIMAL_100);

View File

@ -164,7 +164,7 @@ public class LRUMediaCacheEntryTest {
assertTrue(fakeStream.isClosed()); // all client closed, the main stream should also be closed
assertArrayEquals(new byte[] { 5, 6, 7, 8 }, byteReadFromStream1);
assertArrayEquals(new byte[] { 5, 6, 7, 8 }, byteReadFromStream1);
assertArrayEquals(new byte[] { 5, 6, 7, 8 }, byteReadFromStream2);
// we call the TTS service only once
verify(supplier, times(1)).get();

View File

@ -665,7 +665,7 @@ public class AutomationIntegrationTest extends JavaOSGiTest {
TemplateRegistry<?> templateRegistry = getService(TemplateRegistry.class);
assertThat(templateRegistry, is(notNullValue()));
waitForAssert(() -> {
Template template = null;
Template template;
template = templateRegistry.get("SimpleTestTemplate");
assertThat(template, is(notNullValue()));
assertThat(template.getTags(), is(notNullValue()));
@ -713,7 +713,7 @@ public class AutomationIntegrationTest extends JavaOSGiTest {
TemplateRegistry<?> templateRegistry = getService(TemplateRegistry.class);
assertThat(templateRegistry, is(notNullValue()));
waitForAssert(() -> {
Template template = null;
Template template;
template = templateRegistry.get("TestTemplateWithCompositeModules");
assertThat(template, is(notNullValue()));
assertThat(template.getTags(), is(notNullValue()));

View File

@ -22,6 +22,8 @@ import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openhab.core.automation.Action;
import org.openhab.core.automation.Condition;
import org.openhab.core.automation.Rule;
@ -95,7 +97,8 @@ public class ScriptRuleOSGiTest extends JavaOSGiTest {
registerService(eventSubscriber);
}
// ignore - wip @Test
@Test
@Disabled("WIP")
public void testPredefinedRule() throws ItemNotFoundException {
EventPublisher eventPublisher = getService(EventPublisher.class);
ItemRegistry itemRegistry = getService(ItemRegistry.class);

View File

@ -926,15 +926,15 @@ public class ConfigDispatcherOSGiTest extends JavaOSGiTest {
}
private @Nullable Configuration getConfigurationWithContext(String pidWithContext) {
String pid = null;
String configContext = null;
String pid;
String configContext;
if (pidWithContext.contains(OpenHAB.SERVICE_CONTEXT_MARKER)) {
pid = pidWithContext.split(OpenHAB.SERVICE_CONTEXT_MARKER)[0];
configContext = pidWithContext.split(OpenHAB.SERVICE_CONTEXT_MARKER)[1];
} else {
throw new IllegalArgumentException("PID does not have a context");
}
Configuration[] configs = null;
Configuration[] configs;
try {
configs = configAdmin.listConfigurations(
"(&(service.factoryPid=" + pid + ")(" + OpenHAB.SERVICE_CONTEXT + "=" + configContext + "))");

View File

@ -23,7 +23,6 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@ -158,12 +157,14 @@ public class GenericItemProviderTest extends JavaOSGiTest {
Collection<Item> items = itemRegistry.getAll();
assertThat(items, hasSize(0));
String model = "Group Weather [TAG1]\n" + "Group Weather_Chart (Weather)\n"
+ "Number Weather_Temperature \"Outside Temperature [%.1f °C]\" <temperature> (Weather_Chart) [TAG1, TAG2] { channel=\"acmeweather:weather:berlin:temperature\" }\n"
+ "Number Weather_Temp_Max \"Todays Maximum [%.1f °C]\" <temperature> (Weather_Chart)\n"
+ "Number Weather_Temp_Min \"Todays Minimum [%.1f °C]\" <temperature> (Weather_Chart)\n"
+ "Number Weather_Chart_Period \"Chart Period\"\n"
+ "DateTime Weather_LastUpdate \"Last Update [%1$ta %1$tR]\" <clock> [TAG1, TAG2, TAG3]";
String model = """
Group Weather [TAG1]
Group Weather_Chart (Weather)
Number Weather_Temperature "Outside Temperature [%.1f °C]" <temperature> (Weather_Chart) [TAG1, TAG2] { channel="acmeweather:weather:berlin:temperature" }
Number Weather_Temp_Max "Todays Maximum [%.1f °C]" <temperature> (Weather_Chart)
Number Weather_Temp_Min "Todays Minimum [%.1f °C]" <temperature> (Weather_Chart)
Number Weather_Chart_Period "Chart Period"
DateTime Weather_LastUpdate "Last Update [%1$ta %1$tR]" <clock> [TAG1, TAG2, TAG3]""";
modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));
Collection<Item> actualItems = itemRegistry.getAll();
@ -368,9 +369,10 @@ public class GenericItemProviderTest extends JavaOSGiTest {
public void assertThatTheItemRegistryGetsTheSameInstanceOnItemUpdatesWithoutChanges() throws Exception {
assertThat(itemRegistry.getAll(), hasSize(0));
String model = "String test1 \"Test Item [%s]\" { channel=\"test:test:test:test\" }\n"
+ "String test2 \"Test Item [%s]\" { channel=\"test:test:test:test\" }\n"
+ "String test3 \"Test Item [%s]\" { channel=\"test:test:test:test\" }";
String model = """
String test1 "Test Item [%s]" { channel="test:test:test:test" }
String test2 "Test Item [%s]" { channel="test:test:test:test" }
String test3 "Test Item [%s]" { channel="test:test:test:test" }""";
modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));
waitForAssert(() -> assertThat(itemRegistry.getAll(), hasSize(3)));
@ -420,9 +422,7 @@ public class GenericItemProviderTest extends JavaOSGiTest {
assertThat(groupItem, is(notNullValue()));
int number = 0;
Iterator<Item> it = groupItem.getMembers().iterator();
while (it.hasNext()) {
Item item = it.next();
for (Item item : groupItem.getMembers()) {
assertThat(item.getName(), is("number" + (++number)));
}
}
@ -459,9 +459,7 @@ public class GenericItemProviderTest extends JavaOSGiTest {
assertThat(groupItem, is(notNullValue()));
int number = 0;
Iterator<Item> it = groupItem.getMembers().iterator();
while (it.hasNext()) {
Item item = it.next();
for (Item item : groupItem.getMembers()) {
assertThat(item.getName(), is("number" + (++number)));
if (number == 7) {
assertThat(item.getLabel(), is("Number Seven"));

View File

@ -419,8 +419,10 @@ public class GenericThingProviderTest extends JavaOSGiTest {
public void assertThatStandaloneThingsCanHaveBridgesInLongNotation() {
assertThat(thingRegistry.getAll().size(), is(0));
String model = "Bridge hue:bridge:myBridge @ \"basement\" [ ip = \"1.2.3.4\", username = \"123\" ]\n"
+ "hue:LCT001:bulb1 (hue:bridge:myBridge) [ lightId = \"1\" ] { Switch : notification }\n";
String model = """
Bridge hue:bridge:myBridge @ "basement" [ ip = "1.2.3.4", username = "123" ]
hue:LCT001:bulb1 (hue:bridge:myBridge) [ lightId = "1" ] { Switch : notification }
""";
modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));
Collection<Thing> actualThings = thingRegistry.getAll();
@ -462,8 +464,10 @@ public class GenericThingProviderTest extends JavaOSGiTest {
public void assertThatStandaloneThingWithoutAbridgeDoesNotWorkInShortNotation() {
assertThat(thingRegistry.getAll().size(), is(0));
String model = "LCT001 bulb1 [ lightId = \"1\" ] { Switch : notification }\n"
+ "hue:LCT001:bulb2 (hue:bridge:myBridge) [ lightId = \"2\" ] { Switch : notification }\n";
String model = """
LCT001 bulb1 [ lightId = "1" ] { Switch : notification }
hue:LCT001:bulb2 (hue:bridge:myBridge) [ lightId = "2" ] { Switch : notification }
""";
modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));
Collection<Thing> actualThings = thingRegistry.getAll();

View File

@ -66,19 +66,21 @@ public class GenericThingProviderTest2 extends JavaOSGiTest {
Collection<Thing> things = thingRegistry.getAll();
assertThat(things.size(), is(0));
String model = "Bridge Xhue:Xbridge:myBridge [ XipAddress = \"1.2.3.4\", XuserName = \"123\" ] {" + //
" XLCT001 bulb1 [ XlightId = \"1\" ] { Switch : notification }" + //
" Bridge Xbridge myBridge2 [ ] {" + //
" XLCT001 bulb2 [ ]" + //
" }" + //
"}" + //
"Xhue:XTEST:bulb4 [ XlightId = \"5\"]{" + //
" Switch : notification [ duration = \"5\" ]" + //
"}" + //
"" + //
"Xhue:XLCT001:bulb3 [ XlightId = \"4\" ] {" + //
" Switch : notification [ duration = \"5\" ]" + //
"}";
String model = """
Bridge Xhue:Xbridge:myBridge [ XipAddress = "1.2.3.4", XuserName = "123" ] {
XLCT001 bulb1 [ XlightId = "1" ] { Switch : notification }
Bridge Xbridge myBridge2 [ ] {
XLCT001 bulb2 [ ]
}
}
Xhue:XTEST:bulb4 [ XlightId = "5"] {
Switch : notification [ duration = "5" ]
}
Xhue:XLCT001:bulb3 [ XlightId = "4" ] {
Switch : notification [ duration = "5" ]
}
""";
modelRepository.addOrRefreshModel(TESTMODEL_NAME, new ByteArrayInputStream(model.getBytes()));
Collection<Thing> actualThings = thingRegistry.getAll();
@ -87,7 +89,6 @@ public class GenericThingProviderTest2 extends JavaOSGiTest {
registerService(hueThingHandlerFactory, ThingHandlerFactory.class.getName());
actualThings = thingRegistry.getAll();
assertThat(thingRegistry.getAll().size(), is(6));
unregisterService(hueThingHandlerFactory);

View File

@ -114,7 +114,7 @@ public class JsonStorageServiceOSGiTest extends JavaOSGiTest {
@Test
public void testOverride() {
PersistedItem pItem = null;
PersistedItem pItem;
assertThat(storage.getKeys().size(), is(0));

View File

@ -295,7 +295,7 @@ public class ChannelLinkNotifierOSGiTest extends JavaOSGiTest {
}
private void forEachThingChannelUID(Thing thing, Consumer<ChannelUID> consumer) {
thing.getChannels().stream().map(Channel::getUID).forEach(consumer::accept);
thing.getChannels().stream().map(Channel::getUID).forEach(consumer);
}
private void addItemsAndLinks(Thing thing, String itemSuffix) {

View File

@ -14,7 +14,6 @@ package org.openhab.core.tools.i18n.plugin;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -123,9 +122,7 @@ public class Translations {
}
public Stream<String> keysStream() {
return groups.stream() //
.map(TranslationsGroup::keysStream) //
.flatMap(Function.identity());
return groups.stream().flatMap(TranslationsGroup::keysStream);
}
public Stream<String> linesStream() {
@ -138,8 +135,7 @@ public class Translations {
}
groups.stream() //
.filter(TranslationsGroup::hasTranslations) //
.map(TranslationsGroup::linesStream) //
.flatMap(Function.identity()) //
.flatMap(TranslationsGroup::linesStream) //
.forEach(builder::add);
builder.add("");
return builder.build();
@ -181,16 +177,13 @@ public class Translations {
}
public Stream<String> keysStream() {
return sections.stream() //
.map(TranslationsSection::keysStream) //
.flatMap(Function.identity());
return sections.stream().flatMap(TranslationsSection::keysStream);
}
public Stream<String> linesStream() {
return sections.stream() //
.filter(TranslationsSection::hasTranslations) //
.map(TranslationsSection::linesStream) //
.flatMap(Function.identity());
.flatMap(TranslationsSection::linesStream);
}
public void removeEntries(Predicate<? super TranslationsEntry> filter) {