Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public class RemoteInvocationHandler implements InvocationHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteInvocationHandler.class);

// CHECKSTYLE:OFF
AbstractConnection conn;
RemoteObject remote;
private final AbstractConnection conn;
private final RemoteObject remote;
// CHECKSTYLE:ON

public RemoteInvocationHandler(AbstractConnection _conn, RemoteObject _remote) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public static <T extends Struct> void convertToStructCollection(Collection<Objec
if (constructorArgClasses.length != object.length) {
throw new IllegalArgumentException("Struct length does not match argument length");
}
T x = createStruct(constructorArgClasses, (Object) object, _structType);
T x = createStruct(constructorArgClasses, object, _structType);
_result.add(x);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public static BusAddress of(String _address) {
throw new InvalidBusAddressException("Bus address is blank");
}

BusAddress busAddress = new BusAddress((BusAddress) null);
BusAddress busAddress = new BusAddress(null);

LOGGER.trace("Parsing bus address: {}", _address);

Expand Down
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explanation: The variable _sock is of type SocketChannel which implements NetworkChannel. So, the check _sock instanceof NetworkChannel can only be false if it is null. The else branch can then only be entered if it is indeed null. I wondered... Doesn't aut.getUid(null) always return -1? There might be more code that could be removed.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this is a bigger bug you discovered.

When you check where getUid() is implemented, the code should return something more useful than -1 when a non-null value is given. I'll take a look at that.

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import java.io.*;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.NetworkChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
Expand Down Expand Up @@ -600,14 +599,14 @@ public boolean auth(SocketChannel _sock, AbstractTransport _transport) throws IO
switch (state) {
case INITIAL_STATE:
ByteBuffer buf = ByteBuffer.allocate(1);
if (_sock instanceof NetworkChannel) {
if (_sock != null) {
_sock.read(buf); // 0
state = SaslAuthState.WAIT_AUTH;
} else {
try {
int kuid = -1;
if (_transport instanceof AbstractUnixTransport aut) {
kuid = aut.getUid(_sock);
kuid = aut.getUid(null);
}
if (kuid >= 0) {
kernelUid = stupidlyEncode("" + kuid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
* Abstract class containing methods for handling DBus properties and {@link DBusBoundProperty} annotation. <br>
Expand Down Expand Up @@ -125,9 +124,9 @@ protected PropHandled handleGetAll(ExportedObject _exportObject, final MethodCal
Object val = invokeMethod(_methodCall, propMeth, object);

// when the value is a collection, array or map, wrap them in a proper variant type
if (val != null && val.getClass().isArray() || Collection.class.isInstance(val) || Map.class.isInstance(val)) {
if (val != null && val.getClass().isArray() || val instanceof Collection || val instanceof Map) {
String[] dataType = Marshalling.getDBusType(propEn.getValue().getGenericReturnType());
String dataTypeStr = Arrays.stream(dataType).collect(Collectors.joining());
String dataTypeStr = String.join("", dataType);
getLogger().trace("Creating embedded Array/Collection/Map of type {}", dataTypeStr);
val = new Variant<>(val, dataTypeStr);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public synchronized void remove(String _path) {
}

public synchronized ExportedObject get(String _path) {
int best = 0;
ExportedObject bestobject = null;
String[] pathel = _path.split("/");
for (Map.Entry<String[], ExportedObject> entry : fallbacks.entrySet()) {
Expand All @@ -48,7 +47,7 @@ public synchronized ExportedObject get(String _path) {
break;
}
}
if (i > 0 && i == fbpath.length && i > best) {
if (i > 0 && i == fbpath.length) {
bestobject = entry.getValue();
}
logger.trace("Matches {} bestobject now {}", i, bestobject);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,11 @@ public void terminate() {
@Override
public void run() {

Message msg;
while (!terminate) {
msg = null;

// read from the wire
try {
// this blocks on outgoing being non-empty or a message being available.
msg = connection.readIncoming();
Message msg = connection.readIncoming();
if (msg != null) {
logger.trace("Read message from {}: {}", connection.getTransport(), msg);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,11 @@ public void register() throws DBusException {
}

/**
* Do some action with the currently registered names in a synchronized manor.
* Do some action with the currently registered names in a synchronized manner.
*
* @param _exClz exception type which may be thrown
* @param _action action to execute
* @param <X> type of exception
*
* @return whatever the action returns
*
* @throws X thrown when action throws
*/
private <T> T doWithBusNamesAndReturn(Function<List<String>, T> _action) {
if (_action == null) {
Expand All @@ -152,13 +148,9 @@ private <T> T doWithBusNamesAndReturn(Function<List<String>, T> _action) {
}

/**
* Do some action with the currently registered names in a synchronized manor.
* Do some action with the currently registered names in a synchronized manner.
*
* @param _exClz exception type which may be thrown
* @param _action action to execute
* @param <X> type of exception
*
* @throws X thrown when action throws
*/
private void doWithBusNames(Consumer<List<String>> _action) {
doWithBusNamesAndReturn(bn -> {
Expand Down Expand Up @@ -302,7 +294,7 @@ public void requestBusName(String _busname) throws DBusException {
* @return unique name
*/
public String getUniqueName() {
return doWithBusNamesAndReturn(bn -> bn.getFirst());
return doWithBusNamesAndReturn(List::getFirst);
}

/**
Expand All @@ -311,11 +303,7 @@ public String getUniqueName() {
* @return connection names
*/
public String[] getNames() {
return doWithBusNamesAndReturn(bn -> {
Set<String> names = new TreeSet<>();
names.addAll(bn);
return names;
}).toArray(String[]::new);
return doWithBusNamesAndReturn(TreeSet::new).toArray(String[]::new);
}

@Override
Expand Down Expand Up @@ -514,7 +502,7 @@ public <T extends DBusSignal> AutoCloseable addSigHandler(DBusMatchRule _rule, D
try {
dbus.AddMatch(_rule.toString());
} catch (DBusExecutionException _ex) {
logger.debug("Cannot add match rule: " + _rule.toString(), _ex);
logger.debug("Cannot add match rule: {}", _rule, _ex);
throw new DBusException("Cannot add match rule.", _ex);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,23 +121,21 @@ private static BusAddress validateTransportAddress(BusAddress _address) {
throw new IllegalArgumentException("No transports found to connect to DBus. Please add at least one transport provider to your classpath");
}

BusAddress address = _address;

// no unix transport but address wants to use a unix socket
if (!TransportBuilder.getRegisteredBusTypes().contains("UNIX")
&& address != null
&& address.isBusType("UNIX")) {
&& _address != null
&& _address.isBusType("UNIX")) {
throw new AddressResolvingException("No transports found to handle UNIX socket connections. Please add a unix-socket transport provider to your classpath");
}

// no tcp transport but TCP address given
if (!TransportBuilder.getRegisteredBusTypes().contains("TCP")
&& address != null
&& address.isBusType("TCP")) {
&& _address != null
&& _address.isBusType("TCP")) {
throw new AddressResolvingException("No transports found to handle TCP connections. Please add a TCP transport provider to your classpath");
}

return address;
return _address;

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ default <I extends DBusInterface> I getPeerRemoteObject(String _busname, DBusPat
* happens, try specifying the interface explicitly.
*
* @param _busname
* The bus name to connect to. Usually a well known bus name name in dot-notation (such as
* The bus name to connect to. Usually a well known bus name in dot-notation (such as
* "org.freedesktop.local") or may be a DBus address such as ":1-16".
* @param _objectpath
* The path on which the process is exporting the object.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,6 @@ private void authenticate(SocketChannel _sock) throws IOException {
* The default implementation does not support file descriptor passing!
*
* @param _socket socket to use
* @param _messageFactory message factory
* @return TransportConnection with configured socket channel, reader and writer
*/
private TransportConnection createInputOutput(SocketChannel _socket) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,6 @@ public static TransportBuilder create() {
* @param _address address, never null
*
* @return new {@link TransportBuilder}
* @throws DBusException if invalid address provided
*/
public static TransportBuilder create(BusAddress _address) {
Objects.requireNonNull(_address, "BusAddress required");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public final class DBusMatchRule {
private final Map<MatchRuleField, String> fields = new TreeMap<>();
private final Map<MatchRuleField, Map<Integer, String>> multiValueFields = new TreeMap<>();

protected DBusMatchRule(Map<MatchRuleField, String> _values, Map<MatchRuleField, Map<Integer, String>> _multiValues) {
DBusMatchRule(Map<MatchRuleField, String> _values, Map<MatchRuleField, Map<Integer, String>> _multiValues) {
fields.putAll(Objects.requireNonNull(_values, "Values required"));
if (_multiValues != null) {
multiValueFields.putAll(_multiValues);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public DBusMatchRuleBuilder withMember(String _member) {
*/
public DBusMatchRuleBuilder withType(String _type) {
if (Stream.of(MessageTypes.values())
.map(e -> e.getMatchRuleName())
.map(MessageTypes::getMatchRuleName)
.noneMatch(e -> e.equals(_type))) {
throw new IllegalArgumentException(_type + " is not a valid message type");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,23 @@

import org.freedesktop.dbus.messages.Message;
import org.freedesktop.dbus.messages.constants.MessageTypes;
import org.freedesktop.dbus.utils.Util;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.BiPredicate;

public enum MatchRuleField {
TYPE((m, s) -> Util.strEquals(MessageTypes.getRuleNameById(m.getType()), s), null),
SENDER((m, s) -> Util.strEquals(m.getSource(), s), null),
INTERFACE((m, s) -> Util.strEquals(m.getInterface(), s), null),
MEMBER((m, s) -> Util.strEquals(m.getName(), s), null),
PATH((m, s) -> Util.strEquals(m.getPath(), s), null),
TYPE((m, s) -> Objects.equals(MessageTypes.getRuleNameById(m.getType()), s), null),
SENDER((m, s) -> Objects.equals(m.getSource(), s), null),
INTERFACE((m, s) -> Objects.equals(m.getInterface(), s), null),
MEMBER((m, s) -> Objects.equals(m.getName(), s), null),
PATH((m, s) -> Objects.equals(m.getPath(), s), null),
PATH_NAMESPACE((m, s) -> MatchRuleMatcher.matchPathNamespace(m.getPath(), s), null),
DESTINATION((m, s) -> Util.strEquals(m.getDestination(), s), null),
ARG0123(null, (m, s) -> MatchRuleMatcher.matchArg0123(m, s)),
ARG0123PATH(null, (m, s) -> MatchRuleMatcher.matchArg0123Path(m, s)),
ARG0NAMESPACE((m, s) -> MatchRuleMatcher.matchArg0Namespace(m, s), null);
DESTINATION((m, s) -> Objects.equals(m.getDestination(), s), null),
ARG0123(null, MatchRuleMatcher::matchArg0123),
ARG0123PATH(null, MatchRuleMatcher::matchArg0123Path),
ARG0NAMESPACE(MatchRuleMatcher::matchArg0Namespace, null);

private final BiPredicate<Message, String> singleMatcher;
private final BiPredicate<Message, Map<Integer, String>> multiMatcher;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
import org.freedesktop.dbus.exceptions.DBusExecutionException;
import org.freedesktop.dbus.messages.Message;
import org.freedesktop.dbus.utils.DBusObjects;
import org.freedesktop.dbus.utils.Util;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

final class MatchRuleMatcher {

Expand Down Expand Up @@ -159,7 +159,7 @@ static boolean matchPathNamespace(String _input, String _compare) {
}

for (int i = 0; i < compareSplit.length; i++) {
if (!Util.strEquals(compareSplit[i], inputSplit[i])) {
if (!Objects.equals(compareSplit[i], inputSplit[i])) {
return false;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ private DBusObjects() {
*/
private static <T, X extends DBusException> T requireBase(T _input, Predicate<T> _validation, Function<String, X> _exSupplier, String _customMessage) throws X {
if (_input == null) {
throw _exSupplier.apply(_customMessage != null ? _customMessage : null);
throw _exSupplier.apply(_customMessage);
} else if (_input instanceof String str && str.isBlank()) {
throw _exSupplier.apply(_customMessage != null ? _customMessage : "<Empty String>");
} else if (!_validation.test(_input)) {
Expand Down Expand Up @@ -194,7 +194,7 @@ public static void requireDBusSignalRule(Class<?> _type, String _source) throws
* @since 5.2.0 - 2025-05-02
*/
public static String requireDBusInterface(String _str) throws InvalidObjectPathException {
if (_str == null || _str.isEmpty() || _str.startsWith(".") || !_str.contains(".")) {
if (_str == null || _str.startsWith(".") || !_str.contains(".")) {
throw new InvalidObjectPathException(_str);
}
return _str;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,42 +1,32 @@
package org.freedesktop.dbus.utils;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* Utility class containing methods dealing with object and primitive class types.
* @since 5.1.1 - 2024-09-15
* @author hypfvieh
*/
public final class PrimitiveUtils {
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = Collections.unmodifiableMap(
new ConcurrentHashMap<>(
Map.of(
Boolean.TYPE, Boolean.class,
Byte.TYPE, Byte.class,
Short.TYPE, Short.class,
Character.TYPE, Character.class,
Integer.TYPE, Integer.class,
Long.TYPE, Long.class,
Float.TYPE, Float.class,
Double.TYPE, Double.class)
)
);
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = Map.of(
Boolean.TYPE, Boolean.class,
Byte.TYPE, Byte.class,
Short.TYPE, Short.class,
Character.TYPE, Character.class,
Integer.TYPE, Integer.class,
Long.TYPE, Long.class,
Float.TYPE, Float.class,
Double.TYPE, Double.class);

private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE = Collections.unmodifiableMap(
new ConcurrentHashMap<>(
Map.of(
Boolean.class, Boolean.TYPE,
Byte.class, Byte.TYPE,
Short.class, Short.TYPE,
Character.class, Character.TYPE,
Integer.class, Integer.TYPE,
Long.class, Long.TYPE,
Float.class, Float.TYPE,
Double.class, Double.TYPE)
)
);
private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE = Map.of(
Boolean.class, Boolean.TYPE,
Byte.class, Byte.TYPE,
Short.class, Short.TYPE,
Character.class, Character.TYPE,
Integer.class, Integer.TYPE,
Long.class, Long.TYPE,
Float.class, Float.TYPE,
Double.class, Double.TYPE);

private PrimitiveUtils() {

Expand All @@ -47,15 +37,15 @@ private PrimitiveUtils() {
* @return unmodifiable map
*/
public static Map<Class<?>, Class<?>> getPrimitiveToWrapperTypes() {
return Collections.unmodifiableMap(PRIMITIVE_TO_WRAPPER);
return PRIMITIVE_TO_WRAPPER;
}

/**
* Map with all wrapper types and the corresponding primitive.
* @return unmodifiable map
*/
public static Map<Class<?>, Class<?>> getWrapperToPrimitiveTypes() {
return Collections.unmodifiableMap(WRAPPER_TO_PRIMITIVE);
return WRAPPER_TO_PRIMITIVE;
}

/**
Expand Down
Loading
Loading