Skip to content

Commit

Permalink
Merge pull request #249 from spannm/dbus-java-lang-lvl-syntactic-suga…
Browse files Browse the repository at this point in the history
…ring

Java language level syntactic sugaring
  • Loading branch information
hypfvieh authored Jan 30, 2024
2 parents 7aa46de + f5937d2 commit bebdc55
Show file tree
Hide file tree
Showing 40 changed files with 130 additions and 238 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public Set<Map.Entry<K, V>> entrySet() {
@SuppressWarnings("unchecked")
public V get(Object _key) {
for (Object[] entry : entries) {
if (_key == entry[0] || _key != null && _key.equals(entry[0])) {
if (Objects.equals(_key, entry[0])) {
return (V) entry[1];
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,9 @@ public boolean equals(Object _obj) {
if (this == _obj) {
return true;
}
if (!(_obj instanceof DBusMatchRule)) {
if (!(_obj instanceof DBusMatchRule other)) {
return false;
}
DBusMatchRule other = (DBusMatchRule) _obj;
return Objects.equals(iface, other.iface) && Objects.equals(member, other.member)
&& Objects.equals(object, other.object) && Objects.equals(source, other.source)
&& Objects.equals(type, other.type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ public class MethodTuple {

public MethodTuple(String _name, String _sig) {
name = _name;
if (null != _sig) {
sig = _sig;
} else {
sig = "";
}
sig = Objects.requireNonNullElse(_sig, "");
logger.trace("new MethodTuple({}, {})", name, sig);
}

Expand All @@ -31,10 +27,9 @@ public boolean equals(Object _obj) {
if (this == _obj) {
return true;
}
if (!(_obj instanceof MethodTuple)) {
if (!(_obj instanceof MethodTuple other)) {
return false;
}
MethodTuple other = (MethodTuple) _obj;
return Objects.equals(name, other.name) && Objects.equals(sig, other.sig);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public Object invoke(Object _proxy, Method _method, Object[] _args) throws Throw
} else if (_method.getName().equals("equals")) {
try {
if (1 == _args.length) {
return Boolean.valueOf(_args[0] != null && remote.equals(((RemoteInvocationHandler) Proxy.getInvocationHandler(_args[0])).remote));
return _args[0] != null && remote.equals(((RemoteInvocationHandler) Proxy.getInvocationHandler(_args[0])).remote);
}
} catch (IllegalArgumentException _exIa) {
return Boolean.FALSE;
Expand Down Expand Up @@ -211,16 +211,16 @@ public static Object executeRemoteMethod(final RemoteObject _ro, final Method _m
}

switch (_syncmethod) {
case CALL_TYPE_ASYNC:
case CALL_TYPE_ASYNC -> {
_conn.sendMessage(call);
return new DBusAsyncReply<>(call, _m, _conn);
case CALL_TYPE_CALLBACK:
}
case CALL_TYPE_CALLBACK -> {
_conn.queueCallback(call, _m, _callback);
_conn.sendMessage(call);
return null;
case CALL_TYPE_SYNC:
_conn.sendMessage(call);
break;
}
case CALL_TYPE_SYNC -> _conn.sendMessage(call);
}

// get reply
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ public RemoteObject(String _busname, String _objectpath, Class<? extends DBusInt

@Override
public boolean equals(Object _o) {
if (!(_o instanceof RemoteObject)) {
if (!(_o instanceof RemoteObject them)) {
return false;
}
RemoteObject them = (RemoteObject) _o;

if (!them.objectpath.equals(this.objectpath)) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public static <T extends Struct> void convertToStructCollection(Collection<Objec

Class<?>[] constructorArgClasses = Arrays.stream(_structType.getDeclaredFields())
.filter(f -> f.isAnnotationPresent(Position.class))
.sorted((f1, f2) -> Integer.compare(f1.getAnnotation(Position.class).value(), f2.getAnnotation(Position.class).value()))
.sorted(Comparator.comparingInt(f -> f.getAnnotation(Position.class).value()))
.map(Field::getType)
.toArray(Class[]::new);

Expand Down Expand Up @@ -137,7 +137,7 @@ public static <T extends Struct> T createStructFromVariant(Variant<?> _variant,
}

if (_variant.getType() instanceof DBusStructType && _variant.getValue() instanceof Object[]) {
Class<?>[] argTypes = Arrays.stream((Object[]) _variant.getValue()).map(Object::getClass).toArray(size -> new Class<?>[size]);
Class<?>[] argTypes = Arrays.stream((Object[]) _variant.getValue()).map(Object::getClass).toArray(Class<?>[]::new);
return createStruct(argTypes, _variant.getValue(), _structClass);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -869,10 +869,9 @@ public boolean equals(Object _obj) {
if (this == _obj) {
return true;
}
if (!(_obj instanceof Pair)) {
if (!(_obj instanceof Pair<?, ?> other)) {
return false;
}
Pair<?, ?> other = (Pair<?, ?>) _obj;
return Objects.equals(first, other.first) && Objects.equals(second, other.second);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ private static Class<?>[] createTypesArray(Object... _parameters) {
return null;
}
return Arrays.stream(_parameters)
.filter(p -> p != null) // do no try to convert null values to concrete class
.filter(Objects::nonNull) // do no try to convert null values to concrete class
.map(p -> {
if (List.class.isAssignableFrom(p.getClass())) { // turn possible List subclasses (e.g. ArrayList) to interface class List
return List.class;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ Message readIncoming() throws DBusException {
m = getTransport().readMessage();
} catch (IOException _exIo) {
if (_exIo instanceof EOFException || _exIo instanceof ClosedByInterruptException) {
disconnectCallback.ifPresent(cb -> cb.clientDisconnect());
disconnectCallback.ifPresent(IDisconnectCallback::clientDisconnect);
if (disconnecting // when we are already disconnecting, ignore further errors
|| getBusAddress().isListeningSocket()) { // when we are listener, a client may disconnect any time which
// is no error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -572,13 +572,7 @@ public <T extends DBusSignal> AutoCloseable addSigHandler(Class<T> _type, String
throws DBusException {
validateSignal(_type, _source);
addSigHandler(new DBusMatchRule(_type, _source, null), (DBusSigHandler<? extends DBusSignal>) _handler);
return new AutoCloseable() {

@Override
public void close() throws DBusException {
removeSigHandler(_type, _source, _handler);
}
};
return () -> removeSigHandler(_type, _source, _handler);
}

/**
Expand Down Expand Up @@ -609,12 +603,7 @@ public <T extends DBusSignal> AutoCloseable addSigHandler(Class<T> _type, String
String objectPath = getImportedObjects().get(_object).getObjectPath();
DBusObjects.requireObjectPath(objectPath);
addSigHandler(new DBusMatchRule(_type, _source, objectPath), (DBusSigHandler<? extends DBusSignal>) _handler);
return new AutoCloseable() {
@Override
public void close() throws DBusException {
removeSigHandler(_type, _source, _object, _handler);
}
};
return () -> removeSigHandler(_type, _source, _object, _handler);
}

/**
Expand Down Expand Up @@ -664,12 +653,7 @@ public <T extends DBusSignal> AutoCloseable addSigHandler(DBusMatchRule _rule, D
throw new DBusException("Cannot add match rule.", _ex);
}
}
return new AutoCloseable() {
@Override
public void close() throws DBusException {
removeSigHandler(_rule, _handler);
}
};
return () -> removeSigHandler(_rule, _handler);
}

/**
Expand Down Expand Up @@ -728,7 +712,7 @@ public synchronized void disconnect() {
// remove all exported objects before disconnecting
Map<String, ExportedObject> exportedObjects = getExportedObjects();
synchronized (exportedObjects) {
List<String> exportedKeys = exportedObjects.keySet().stream().filter(f -> f != null).collect(Collectors.toList());
List<String> exportedKeys = exportedObjects.keySet().stream().filter(Objects::nonNull).collect(Collectors.toList());
for (String key : exportedKeys) {
unExportObject(key);
}
Expand Down Expand Up @@ -794,12 +778,7 @@ public AutoCloseable addGenericSigHandler(DBusMatchRule _rule, DBusSigHandler<DB
throw new DBusException(_ex.getMessage());
}
}
return new AutoCloseable() {
@Override
public void close() throws DBusException {
removeGenericSigHandler(_rule, _handler);
}
};
return () -> removeGenericSigHandler(_rule, _handler);
}

private final class SigHandler implements DBusSigHandler<DBusSignal> {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.freedesktop.dbus.exceptions;

import java.util.Objects;

/**
* An exception while running a remote method within DBus.
*/
Expand Down Expand Up @@ -37,10 +39,6 @@ public void setType(String _type) {
* @return string
*/
public String getType() {
if (null == type) {
return getClass().getName();
} else {
return type;
}
return Objects.requireNonNullElseGet(type, () -> getClass().getName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ private int appendOne(byte[] _sigb, int _sigofs, Object _data) throws DBusExcept
appendByte(((Number) _data).byteValue());
break;
case BOOLEAN:
appendint(((Boolean) _data).booleanValue() ? 1 : 0, 4);
appendint((Boolean) _data ? 1 : 0, 4);
break;
case DOUBLE:
long l = Double.doubleToLongBits(((Number) _data).doubleValue());
Expand Down Expand Up @@ -614,41 +614,40 @@ private int appendOne(byte[] _sigb, int _sigofs, Object _data) throws DBusExcept
int algn = getAlignment(_sigb[i]);
int len = Array.getLength(_data);
switch (_sigb[i]) {
case BYTE:
primbuf = (byte[]) _data;
break;
case INT16, INT32, INT64:
primbuf = new byte[len * algn];
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Array.getLong(_data, j), primbuf, k, algn);
case BYTE -> {
primbuf = (byte[]) _data;
}
break;
case BOOLEAN:
primbuf = new byte[len * algn];
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Array.getBoolean(_data, j) ? 1 : 0, primbuf, k, algn);
}
break;
case DOUBLE:
primbuf = new byte[len * algn];
if (_data instanceof float[] fa) {
case INT16, INT32, INT64 -> {
primbuf = new byte[len * algn];
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Double.doubleToRawLongBits(fa[j]), primbuf, k, algn);
marshallint(Array.getLong(_data, j), primbuf, k, algn);
}
} else {
}
case BOOLEAN -> {
primbuf = new byte[len * algn];
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Double.doubleToRawLongBits(((double[]) _data)[j]), primbuf, k, algn);
marshallint(Array.getBoolean(_data, j) ? 1 : 0, primbuf, k, algn);
}
}
case DOUBLE -> {
primbuf = new byte[len * algn];
if (_data instanceof float[] fa) {
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Double.doubleToRawLongBits(fa[j]), primbuf, k, algn);
}
} else {
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Double.doubleToRawLongBits(((double[]) _data)[j]), primbuf, k, algn);
}
}
}
break;
case FLOAT:
primbuf = new byte[len * algn];
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Float.floatToRawIntBits(((float[]) _data)[j]), primbuf, k, algn);
case FLOAT -> {
primbuf = new byte[len * algn];
for (int j = 0, k = 0; j < len; j++, k += algn) {
marshallint(Float.floatToRawIntBits(((float[]) _data)[j]), primbuf, k, algn);
}
}
break;
default:
throw new MarshallingException("Primitive array being sent as non-primitive array.");
default -> throw new MarshallingException("Primitive array being sent as non-primitive array.");
}
appendBytes(primbuf);
} else if (_data instanceof List<?> lst) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,9 @@ public boolean equals(Object _obj) {
if (this == _obj) {
return true;
}
if (!(_obj instanceof Variant<?>)) {
if (!(_obj instanceof Variant<?> other)) {
return false;
}
Variant<?> other = (Variant<?>) _obj;
return Objects.equals(value, other.value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ private static File determineMachineIdFile(String _dbusMachineIdFile) {
List<String> locationPriorityList = Arrays.asList(System.getenv(DBusSysProps.DBUS_MACHINE_ID_SYS_VAR), _dbusMachineIdFile,
"/var/lib/dbus/machine-id", "/usr/local/var/lib/dbus/machine-id", "/etc/machine-id");
return locationPriorityList.stream()
.filter(s -> s != null)
.filter(Objects::nonNull)
.map(File::new)
.filter(f -> f.exists() && f.length() > 0)
.findFirst()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,7 @@ public TimeMeasure(ITimeMeasureFormat _formatter) {
* Create a new instance, used a formatter converting everything &gt;= 5000 ms to seconds (X.Y -&gt; 6.1).
*/
public TimeMeasure() {
this(new ITimeMeasureFormat() {
@Override
public String format(long _durationInMillis) {
return _durationInMillis >= 5000 ? ((long) ((_durationInMillis / 1000d) * 10) / 10d) + "s" : _durationInMillis + "ms";
}
});
this(_durationInMillis -> _durationInMillis >= 5000 ? ((long) ((_durationInMillis / 1000d) * 10) / 10d) + "s" : _durationInMillis + "ms");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,8 @@ public static <T> boolean collectionContainsAny(Collection<T> _haystack, Collect
*/
public static String getCurrentUser() {
String[] sysPropParms = new String[] {"user.name", "USER", "USERNAME"};
for (int i = 0; i < sysPropParms.length; i++) {
String val = System.getProperty(sysPropParms[i]);
for (String sysPropParm : sysPropParms) {
String val = System.getProperty(sysPropParm);
if (!isEmpty(val)) {
return val;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ public String getObjectPath() {

@Override
public List<String> getPartNames() {
return parts.stream().map(i -> i.getVal1()).collect(Collectors.toList());
return parts.stream().map(MyInterfacePart::getVal1).collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,7 @@ ExecutorService getExecutor(ExecutorNames _executor) {
*/
@Test
void testRetryHandlerHardLimit() {
IThreadPoolRetryHandler handler = new IThreadPoolRetryHandler() {
@Override
public boolean handle(ExecutorNames _executor, Exception _ex) {
return true;
}
};
IThreadPoolRetryHandler handler = (_executor, _ex) -> true;

ReceivingServiceConfig build = new ReceivingServiceConfigBuilder<>(null).withRetryHandler(handler).build();

Expand Down Expand Up @@ -139,13 +134,9 @@ ExecutorService getExecutor(ExecutorNames _executor) {
@Test
void testRetryHandlerNotCalledBecauseNoFailure() {
AtomicBoolean handlerWasCalled = new AtomicBoolean();
IThreadPoolRetryHandler handler = new IThreadPoolRetryHandler() {

@Override
public boolean handle(ExecutorNames _executor, Exception _ex) {
handlerWasCalled.set(true);
return true;
}
IThreadPoolRetryHandler handler = (_executor, _ex) -> {
handlerWasCalled.set(true);
return true;
};

ReceivingServiceConfig build = new ReceivingServiceConfigBuilder<>(null).withRetryHandler(handler).build();
Expand Down
Loading

0 comments on commit bebdc55

Please sign in to comment.