Fix/suppress PMD CompareObjectsWithEquals findings (#2548)

Newer PMD versions discover more CompareObjectsWithEquals findings.

Related to https://github.com/openhab/static-code-analysis/pull/423

Signed-off-by: Wouter Born <github@maindrain.net>
pull/2552/head
Wouter Born 2021-10-30 19:37:34 +02:00 committed by GitHub
parent 40e23e23ca
commit bf81eaa1c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 35 additions and 20 deletions

View File

@ -93,11 +93,11 @@ public class AudioServlet extends OpenHABServlet implements AudioHTTPServer {
// try to set the content-type, if possible // try to set the content-type, if possible
final String mimeType; final String mimeType;
if (stream.getFormat().getCodec() == AudioFormat.CODEC_MP3) { if (AudioFormat.CODEC_MP3.equals(stream.getFormat().getCodec())) {
mimeType = "audio/mpeg"; mimeType = "audio/mpeg";
} else if (stream.getFormat().getContainer() == AudioFormat.CONTAINER_WAVE) { } else if (AudioFormat.CONTAINER_WAVE.equals(stream.getFormat().getContainer())) {
mimeType = "audio/wav"; mimeType = "audio/wav";
} else if (stream.getFormat().getContainer() == AudioFormat.CONTAINER_OGG) { } else if (AudioFormat.CONTAINER_OGG.equals(stream.getFormat().getContainer())) {
mimeType = "audio/ogg"; mimeType = "audio/ogg";
} else { } else {
mimeType = null; mimeType = null;

View File

@ -81,7 +81,7 @@ public class JavaSoundAudioSink implements AudioSink {
@Override @Override
public synchronized void process(final @Nullable AudioStream audioStream) public synchronized void process(final @Nullable AudioStream audioStream)
throws UnsupportedAudioFormatException, UnsupportedAudioStreamException { throws UnsupportedAudioFormatException, UnsupportedAudioStreamException {
if (audioStream != null && audioStream.getFormat().getCodec() != AudioFormat.CODEC_MP3) { if (audioStream != null && !AudioFormat.CODEC_MP3.equals(audioStream.getFormat().getCodec())) {
AudioPlayer audioPlayer = new AudioPlayer(audioStream); AudioPlayer audioPlayer = new AudioPlayer(audioStream);
audioPlayer.start(); audioPlayer.start();
try { try {

View File

@ -210,6 +210,7 @@ public class OAuthStoreHandlerImpl implements OAuthStoreHandler {
allAvailableStorageCiphers.add(storageCipher); allAvailableStorageCiphers.add(storageCipher);
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
protected synchronized void unsetStorageCipher(StorageCipher storageCipher) { protected synchronized void unsetStorageCipher(StorageCipher storageCipher) {
allAvailableStorageCiphers.remove(storageCipher); allAvailableStorageCiphers.remove(storageCipher);
if (this.storageCipher.isPresent() && this.storageCipher.get() == storageCipher) { if (this.storageCipher.isPresent() && this.storageCipher.get() == storageCipher) {

View File

@ -463,7 +463,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
unregister(oldRule); unregister(oldRule);
} }
if (isEnabled(rUID) == Boolean.TRUE) { if (Boolean.TRUE.equals(isEnabled(rUID))) {
setRule(rule); setRule(rule);
} }
} }
@ -1452,7 +1452,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
private boolean mustTrigger(Rule r) { private boolean mustTrigger(Rule r) {
for (Trigger t : r.getTriggers()) { for (Trigger t : r.getTriggers()) {
if (t.getTypeUID() == SystemTriggerHandler.STARTLEVEL_MODULE_TYPE_ID) { if (SystemTriggerHandler.STARTLEVEL_MODULE_TYPE_ID.equals(t.getTypeUID())) {
Object slObj = t.getConfiguration().get(SystemTriggerHandler.CFG_STARTLEVEL); Object slObj = t.getConfiguration().get(SystemTriggerHandler.CFG_STARTLEVEL);
try { try {
Integer sl = Integer.valueOf(slObj.toString()); Integer sl = Integer.valueOf(slObj.toString());

View File

@ -71,9 +71,9 @@ public class AutomationCommandRemove extends AutomationCommand {
case AutomationCommands.TEMPLATE_PROVIDER: case AutomationCommands.TEMPLATE_PROVIDER:
return autoCommands.remove(AutomationCommands.TEMPLATE_PROVIDER, url); return autoCommands.remove(AutomationCommands.TEMPLATE_PROVIDER, url);
case AutomationCommands.RULE_PROVIDER: case AutomationCommands.RULE_PROVIDER:
if (command == AutomationCommands.REMOVE_RULE) { if (AutomationCommands.REMOVE_RULE.equals(command)) {
return autoCommands.removeRule(id); return autoCommands.removeRule(id);
} else if (command == AutomationCommands.REMOVE_RULES) { } else if (AutomationCommands.REMOVE_RULES.equals(command)) {
return autoCommands.removeRules(id); return autoCommands.removeRules(id);
} }
} }

View File

@ -447,7 +447,7 @@ public abstract class AbstractDiscoveryService implements DiscoveryService {
if (autoDiscoveryEnabled instanceof String) { if (autoDiscoveryEnabled instanceof String) {
return Boolean.valueOf((String) autoDiscoveryEnabled); return Boolean.valueOf((String) autoDiscoveryEnabled);
} else { } else {
return autoDiscoveryEnabled == Boolean.TRUE; return Boolean.TRUE.equals(autoDiscoveryEnabled);
} }
} }

View File

@ -56,6 +56,7 @@ public class ConsoleSupportKaraf {
registerCommands(); registerCommands();
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void unsetSessionFactory(SessionFactory sessionFactory) { public void unsetSessionFactory(SessionFactory sessionFactory) {
if (this.sessionFactory == sessionFactory) { if (this.sessionFactory == sessionFactory) {
unregisterCommands(); unregisterCommands();

View File

@ -133,7 +133,7 @@ public class AddonResource implements RESTResource {
@QueryParam("serviceId") @Parameter(description = "service ID") @Nullable String serviceId) { @QueryParam("serviceId") @Parameter(description = "service ID") @Nullable String serviceId) {
logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath()); logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());
Locale locale = localeService.getLocale(language); Locale locale = localeService.getLocale(language);
if (serviceId == "all") { if ("all".equals(serviceId)) {
return Response.ok(new Stream2JSONInputStream(getAllAddons(locale))).build(); return Response.ok(new Stream2JSONInputStream(getAllAddons(locale))).build();
} else { } else {
AddonService addonService = (serviceId != null) ? getServiceById(serviceId) : getDefaultService(); AddonService addonService = (serviceId != null) ? getServiceById(serviceId) : getDefaultService();

View File

@ -53,6 +53,7 @@ public class BitArray implements Iterable<Boolean> {
return bitSet; return bitSet;
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
private boolean sizeAndValuesEquals(@Nullable Object obj) { private boolean sizeAndValuesEquals(@Nullable Object obj) {
if (obj == null) { if (obj == null) {
return false; return false;

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.core.model.lsp.internal; package org.openhab.core.model.lsp.internal;
import java.util.Objects;
import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl; import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
@ -99,7 +101,7 @@ public class RegistryProvider implements Provider<IResourceServiceProvider.Regis
FileExtensionProvider extensionProvider = injector.getInstance(FileExtensionProvider.class); FileExtensionProvider extensionProvider = injector.getInstance(FileExtensionProvider.class);
for (String ext : extensionProvider.getFileExtensions()) { for (String ext : extensionProvider.getFileExtensions()) {
if (registry.getExtensionToFactoryMap().containsKey(ext)) { if (registry.getExtensionToFactoryMap().containsKey(ext)) {
if (extensionProvider.getPrimaryFileExtension() == ext) { if (Objects.equals(extensionProvider.getPrimaryFileExtension(), ext)) {
registry.getExtensionToFactoryMap().put(ext, resourceServiceProvider); registry.getExtensionToFactoryMap().put(ext, resourceServiceProvider);
} }
} else { } else {

View File

@ -386,6 +386,7 @@ public abstract class BaseThingHandler implements ThingHandler {
* *
* @param thing thing, that was updated and should be persisted * @param thing thing, that was updated and should be persisted
*/ */
@SuppressWarnings("PMD.CompareObjectsWithEquals")
protected void updateThing(Thing thing) { protected void updateThing(Thing thing) {
if (thing == this.thing) { if (thing == this.thing) {
throw new IllegalArgumentException( throw new IllegalArgumentException(

View File

@ -551,6 +551,7 @@ public class ThingManagerImpl
} }
@Override @Override
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void thingUpdated(final Thing thing, ThingTrackerEvent thingTrackerEvent) { public void thingUpdated(final Thing thing, ThingTrackerEvent thingTrackerEvent) {
ThingUID thingUID = thing.getUID(); ThingUID thingUID = thing.getUID();
if (thingUpdatedLock.contains(thingUID)) { if (thingUpdatedLock.contains(thingUID)) {
@ -703,6 +704,7 @@ public class ThingManagerImpl
} }
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
private void initializeHandler(Thing thing) { private void initializeHandler(Thing thing) {
if (isDisabledByStorage(thing.getUID())) { if (isDisabledByStorage(thing.getUID())) {
setThingStatus(thing, buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.DISABLED)); setThingStatus(thing, buildStatusInfo(ThingStatus.UNINITIALIZED, ThingStatusDetail.DISABLED));
@ -834,6 +836,7 @@ public class ThingManagerImpl
return thing.getStatus() == ThingStatus.INITIALIZING; return thing.getStatus() == ThingStatus.INITIALIZING;
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
private boolean isHandlerRegistered(Thing thing) { private boolean isHandlerRegistered(Thing thing) {
ThingHandler handler = thingHandlers.get(thing.getUID()); ThingHandler handler = thingHandlers.get(thing.getUID());
return handler != null && handler == thing.getHandler(); return handler != null && handler == thing.getHandler();

View File

@ -134,7 +134,7 @@ public class SystemHysteresisStateProfile implements StateProfile {
final QuantityType<?> qtState = (QuantityType<?>) value; final QuantityType<?> qtState = (QuantityType<?>) value;
final QuantityType<?> finalLower; final QuantityType<?> finalLower;
final QuantityType<?> finalUpper; final QuantityType<?> finalUpper;
if (lower.getUnit() == Units.ONE && upper.getUnit() == Units.ONE) { if (Units.ONE.equals(lower.getUnit()) && Units.ONE.equals(upper.getUnit())) {
// allow bounds without unit -> implicitly assume its the same as the one from the state, but warn // allow bounds without unit -> implicitly assume its the same as the one from the state, but warn
// the user // the user
finalLower = new QuantityType<>(lower.toBigDecimal(), qtState.getUnit()); finalLower = new QuantityType<>(lower.toBigDecimal(), qtState.getUnit());

View File

@ -115,7 +115,7 @@ public class SystemOffsetProfile implements StateProfile {
if (state instanceof QuantityType) { if (state instanceof QuantityType) {
QuantityType qtState = (QuantityType) state; QuantityType qtState = (QuantityType) state;
try { try {
if (finalOffset.getUnit() == Units.ONE) { if (Units.ONE.equals(finalOffset.getUnit())) {
// allow offsets without unit -> implicitly assume its the same as the one from the state, but warn // allow offsets without unit -> implicitly assume its the same as the one from the state, but warn
// the user // the user
finalOffset = new QuantityType<>(finalOffset.toBigDecimal(), qtState.getUnit()); finalOffset = new QuantityType<>(finalOffset.toBigDecimal(), qtState.getUnit());
@ -135,7 +135,7 @@ public class SystemOffsetProfile implements StateProfile {
} catch (UnconvertibleException e) { } catch (UnconvertibleException e) {
logger.warn("Cannot apply offset '{}' to state '{}' because types do not match.", finalOffset, qtState); logger.warn("Cannot apply offset '{}' to state '{}' because types do not match.", finalOffset, qtState);
} }
} else if (state instanceof DecimalType && finalOffset.getUnit() == Units.ONE) { } else if (state instanceof DecimalType && Units.ONE.equals(finalOffset.getUnit())) {
DecimalType decState = (DecimalType) state; DecimalType decState = (DecimalType) state;
result = new DecimalType(decState.toBigDecimal().add(finalOffset.toBigDecimal())); result = new DecimalType(decState.toBigDecimal().add(finalOffset.toBigDecimal()));
} else { } else {

View File

@ -142,7 +142,7 @@ public class SystemRangeStateProfile implements StateProfile {
final QuantityType<?> qtState = (QuantityType<?>) value; final QuantityType<?> qtState = (QuantityType<?>) value;
final QuantityType<?> finalLower; final QuantityType<?> finalLower;
final QuantityType<?> finalUpper; final QuantityType<?> finalUpper;
if (lower.getUnit() == Units.ONE && upper.getUnit() == Units.ONE) { if (Units.ONE.equals(lower.getUnit()) && Units.ONE.equals(upper.getUnit())) {
// allow bounds without unit -> implicitly assume its the same as the one from the state, but warn // allow bounds without unit -> implicitly assume its the same as the one from the state, but warn
// the user // the user
finalLower = new QuantityType<>(lower.toBigDecimal(), qtState.getUnit()); finalLower = new QuantityType<>(lower.toBigDecimal(), qtState.getUnit());

View File

@ -112,7 +112,7 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
if ((result = rule.execute(language, tokens)).isSuccess()) { if ((result = rule.execute(language, tokens)).isSuccess()) {
return result.getResponse(); return result.getResponse();
} else { } else {
if (result != InterpretationResult.SYNTAX_ERROR) { if (!InterpretationResult.SYNTAX_ERROR.equals(result)) {
lastResult = result; lastResult = result;
} }
} }
@ -855,6 +855,7 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
} }
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void unsetItemRegistry(ItemRegistry itemRegistry) { public void unsetItemRegistry(ItemRegistry itemRegistry) {
if (itemRegistry == this.itemRegistry) { if (itemRegistry == this.itemRegistry) {
this.itemRegistry.removeRegistryChangeListener(registryChangeListener); this.itemRegistry.removeRegistryChangeListener(registryChangeListener);
@ -868,6 +869,7 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
} }
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void unsetEventPublisher(EventPublisher eventPublisher) { public void unsetEventPublisher(EventPublisher eventPublisher) {
if (eventPublisher == this.eventPublisher) { if (eventPublisher == this.eventPublisher) {
this.eventPublisher = null; this.eventPublisher = null;

View File

@ -232,7 +232,7 @@ public class StateDescriptionFragmentImpl implements StateDescriptionFragment {
&& (maximum != null ? maximum.equals(other.maximum) : other.maximum == null) && (maximum != null ? maximum.equals(other.maximum) : other.maximum == null)
&& (step != null ? step.equals(other.step) : other.step == null) && (step != null ? step.equals(other.step) : other.step == null)
&& (pattern != null ? pattern.equals(other.pattern) : other.pattern == null) && (pattern != null ? pattern.equals(other.pattern) : other.pattern == null)
&& readOnly == other.readOnly // && (readOnly != null ? readOnly.equals(other.readOnly) : other.readOnly == null)
&& (options != null ? options.equals(other.options) : other.options == null); && (options != null ? options.equals(other.options) : other.options == null);
} }

View File

@ -363,7 +363,7 @@ public class QuantityType<T extends Quantity<T>> extends Number
@Override @Override
public String toFullString() { public String toFullString() {
if (quantity.getUnit() == AbstractUnit.ONE) { if (AbstractUnit.ONE.equals(quantity.getUnit())) {
return quantity.getValue().toString(); return quantity.getValue().toString();
} else { } else {
return quantity.toString(); return quantity.toString();

View File

@ -165,6 +165,7 @@ public class WatchQueueReader implements Runnable {
} }
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public synchronized void stopWatchService(AbstractWatchService service) { public synchronized void stopWatchService(AbstractWatchService service) {
if (watchService != null) { if (watchService != null) {
List<WatchKey> keys = new LinkedList<>(); List<WatchKey> keys = new LinkedList<>();

View File

@ -71,9 +71,9 @@ public class QuantityTypeTest {
new QuantityType<>("57%"); new QuantityType<>("57%");
QuantityType<Dimensionless> dt0 = new QuantityType<>("12"); QuantityType<Dimensionless> dt0 = new QuantityType<>("12");
assertTrue(dt0.getUnit().getDimension() == UnitDimension.NONE); assertEquals(UnitDimension.NONE, dt0.getUnit().getDimension());
dt0 = new QuantityType<>("2rad"); dt0 = new QuantityType<>("2rad");
assertTrue(dt0.getUnit().getDimension() == UnitDimension.NONE); assertEquals(UnitDimension.NONE, dt0.getUnit().getDimension());
} }
@ParameterizedTest @ParameterizedTest

View File

@ -53,6 +53,7 @@ public class AuthorizationCodeTestAgent extends AbstractTestAgent implements Tes
super.oauthFactory = oauthFactory; super.oauthFactory = oauthFactory;
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void unsetOauthFactory(OAuthFactory oauthFactory) { public void unsetOauthFactory(OAuthFactory oauthFactory) {
if (super.oauthFactory == oauthFactory) { if (super.oauthFactory == oauthFactory) {
if (handle != null) { if (handle != null) {

View File

@ -53,6 +53,7 @@ public class ResourceOwnerTestAgent extends AbstractTestAgent implements TestAge
this.oauthFactory = oauthFactory; this.oauthFactory = oauthFactory;
} }
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void unsetOauthFactory(OAuthFactory oauthFactory) { public void unsetOauthFactory(OAuthFactory oauthFactory) {
if (super.oauthFactory == oauthFactory) { if (super.oauthFactory == oauthFactory) {
if (handle != null) { if (handle != null) {

View File

@ -342,6 +342,7 @@ public class ItemRegistryImplTest extends JavaTest {
} }
@Test @Test
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void assertItemIsBeingDisposedOnRemove() { public void assertItemIsBeingDisposedOnRemove() {
GenericItem item = spy(new SwitchItem("Item1")); GenericItem item = spy(new SwitchItem("Item1"));
itemProvider.add(item); itemProvider.add(item);