Skip to content

Commit

Permalink
Polishing.
Browse files Browse the repository at this point in the history
Tweak naming. Simplify converters by removing unused methods.

See #2754
  • Loading branch information
mp911de committed Oct 27, 2023
1 parent 85e9ae5 commit 667dd27
Show file tree
Hide file tree
Showing 11 changed files with 35 additions and 103 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -171,18 +171,7 @@ public static Map<byte[], Double> toTupleMap(Set<Tuple> tuples) {
return args;
}

public static byte[] toBytes(Integer source) {
return String.valueOf(source).getBytes();
}

public static byte[] toBytes(Long source) {
return String.valueOf(source).getBytes();
}

/**
* @since 1.6
*/
public static byte[] toBytes(Double source) {
public static byte[] toBytes(Number source) {
return toBytes(String.valueOf(source));
}

Expand All @@ -196,10 +185,6 @@ public static String toString(@Nullable byte[] source) {
return source == null ? null : SafeEncoder.encode(source);
}

public static Long toLong(byte[] source) {
return Long.valueOf(toString(source));
}

/**
* Convert the given {@code source} value to the corresponding {@link ValueEncoding}.
*
Expand Down Expand Up @@ -466,16 +451,12 @@ private static byte[] boundaryToBytes(org.springframework.data.domain.Range.Boun
byte[] exclPrefix) {

byte[] prefix = boundary.isInclusive() ? inclPrefix : exclPrefix;
byte[] value = null;
byte[] value;
Object theValue = boundary.getValue().get();
if (theValue instanceof byte[] bytes) {
value = bytes;
} else if (theValue instanceof Double doubleValue) {
value = toBytes(doubleValue);
} else if (theValue instanceof Long longValue) {
value = toBytes(longValue);
} else if (theValue instanceof Integer integer) {
value = toBytes(integer);
} else if (theValue instanceof Number number) {
value = toBytes(number);
} else if (theValue instanceof String string) {
value = toBytes(string);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,29 +45,25 @@ public class JedisExceptionConverter implements Converter<Exception, DataAccessE

public DataAccessException convert(Exception ex) {

if (ex instanceof DataAccessException dataAccessException) {
return dataAccessException;
}

if (ex instanceof UnsupportedOperationException) {
return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
if (ex instanceof DataAccessException dae) {
return dae;
}

if (ex instanceof JedisClusterOperationException && "No more cluster attempts left".equals(ex.getMessage())) {
return new TooManyClusterRedirectionsException(ex.getMessage(), ex);
}

if (ex instanceof JedisRedirectionException redirectionException) {
if (ex instanceof JedisRedirectionException rex) {

return new ClusterRedirectException(redirectionException.getSlot(),
redirectionException.getTargetNode().getHost(), redirectionException.getTargetNode().getPort(), ex);
return new ClusterRedirectException(rex.getSlot(), rex.getTargetNode().getHost(), rex.getTargetNode().getPort(),
ex);
}

if (ex instanceof JedisConnectionException) {
return new RedisConnectionFailureException(ex.getMessage(), ex);
}

if (ex instanceof JedisException) {
if (ex instanceof JedisException || ex instanceof UnsupportedOperationException) {
return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
*/
package org.springframework.data.redis.connection.jedis;

import redis.clients.jedis.util.SafeEncoder;

import java.util.ArrayList;
import java.util.List;

Expand All @@ -41,7 +39,7 @@ public JedisScriptReturnConverter(ReturnType returnType) {
public Object convert(@Nullable Object result) {
if (result instanceof String stringResult) {
// evalsha converts byte[] to String. Convert back for consistency
return SafeEncoder.encode(stringResult);
return JedisConverters.toBytes(stringResult);
}
if (returnType == ReturnType.STATUS) {
return JedisConverters.toString((byte[]) result);
Expand All @@ -60,7 +58,7 @@ public Object convert(@Nullable Object result) {
if (res instanceof String stringResult) {
// evalsha converts byte[] to String. Convert back for
// consistency
convertedResults.add(SafeEncoder.encode(stringResult));
convertedResults.add(JedisConverters.toBytes(stringResult));
} else {
convertedResults.add(res);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import redis.clients.jedis.params.XReadParams;
import redis.clients.jedis.resps.StreamEntry;
import redis.clients.jedis.resps.StreamPendingEntry;
import redis.clients.jedis.util.SafeEncoder;

import java.time.Duration;
import java.util.ArrayList;
Expand Down Expand Up @@ -132,7 +131,7 @@ static List<ByteRecord> convertToByteRecord(byte[] key, Object source) {
continue;
}

String entryIdString = SafeEncoder.encode((byte[]) res.get(0));
String entryIdString = JedisConverters.toString((byte[]) res.get(0));
List<byte[]> hash = (List<byte[]>) res.get(1);

Iterator<byte[]> hashIterator = hash.iterator();
Expand Down Expand Up @@ -163,19 +162,19 @@ static PendingMessagesSummary toPendingMessagesSummary(String groupName, Object
List<Object> objectList = (List<Object>) source;
long total = BuilderFactory.LONG.build(objectList.get(0));
Range.Bound<String> lower = objectList.get(1) != null
? Range.Bound.inclusive(SafeEncoder.encode((byte[]) objectList.get(1)))
? Range.Bound.inclusive(JedisConverters.toString((byte[]) objectList.get(1)))
: Range.Bound.unbounded();
Range.Bound<String> upper = objectList.get(2) != null
? Range.Bound.inclusive(SafeEncoder.encode((byte[]) objectList.get(2)))
? Range.Bound.inclusive(JedisConverters.toString((byte[]) objectList.get(2)))
: Range.Bound.unbounded();
List<List<Object>> consumerObjList = (List<List<Object>>) objectList.get(3);
Map<String, Long> map;

if (consumerObjList != null) {
map = new HashMap<>(consumerObjList.size());
for (List<Object> consumerObj : consumerObjList) {
map.put(SafeEncoder.encode((byte[]) consumerObj.get(0)),
Long.parseLong(SafeEncoder.encode((byte[]) consumerObj.get(1))));
map.put(JedisConverters.toString((byte[]) consumerObj.get(0)),
Long.parseLong(JedisConverters.toString((byte[]) consumerObj.get(1))));
}
} else {
map = Collections.emptyMap();
Expand All @@ -185,7 +184,7 @@ static PendingMessagesSummary toPendingMessagesSummary(String groupName, Object
}

/**
* Convert the raw Jedis xpending result to {@link PendingMessages}.
* Convert the raw Jedis {@code xpending} result to {@link PendingMessages}.
*
* @param groupName the group name
* @param range the range of messages requested
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public DataAccessException convert(Exception ex) {
return new RedisSystemException("Error in execution", ex);
}

if (ex instanceof DataAccessException dataAccessException) {
return dataAccessException;
if (ex instanceof DataAccessException dae) {
return dae;
}

if (ex instanceof RedisCommandInterruptedException) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@
import io.lettuce.core.models.stream.PendingMessage;
import io.lettuce.core.models.stream.PendingMessages;

import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.convert.converter.Converter;
Expand All @@ -34,9 +32,6 @@
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamReadOptions;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.util.ByteUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.NumberUtils;

/**
* Converters for Redis Stream-specific types.
Expand Down Expand Up @@ -76,10 +71,6 @@ static Converter<StreamMessage<byte[], byte[]>, ByteRecord> byteRecordConverter(
return (it) -> StreamRecords.newRecord().in(it.getStream()).withId(it.getId()).ofBytes(it.getBody());
}

static Converter<StreamMessage<byte[], byte[]>, RecordId> messageToIdConverter() {
return (it) -> RecordId.of(it.getId());
}

/**
* Convert the raw Lettuce xpending result to {@link PendingMessages}.
*
Expand All @@ -106,7 +97,7 @@ static org.springframework.data.redis.connection.stream.PendingMessages toPendin
}

/**
* Convert the raw Lettuce xpending result to {@link PendingMessagesSummary}.
* Convert the raw Lettuce {@code xpending} result to {@link PendingMessagesSummary}.
*
* @param groupName
* @param source the raw lettuce response.
Expand All @@ -123,38 +114,6 @@ static PendingMessagesSummary toPendingMessagesInfo(String groupName, PendingMes
return new PendingMessagesSummary(groupName, source.getCount(), range, source.getConsumerMessageCount());
}

/**
* We need to convert values into the correct target type since lettuce will give us {@link ByteBuffer} or arrays but
* the parser requires us to have them as {@link String} or numeric values. Oh and {@literal null} values aren't real
* good citizens as well, so we make them empty strings instead - see it works - somehow ;P
*
* @param value dont't get me started om this.
* @return preconverted values that Lettuce parsers are able to understand \ö/.
*/
private static Object preConvertNativeValues(@Nullable Object value) {

if (value instanceof ByteBuffer || value instanceof byte[]) {

byte[] targetArray = value instanceof ByteBuffer byteBuffer ? ByteUtils.getBytes(byteBuffer) : (byte[]) value;
String tmp = LettuceConverters.toString(targetArray);

try {
return NumberUtils.parseNumber(tmp, Long.class);
} catch (NumberFormatException ex) {
return tmp;
}
}
if (value instanceof List listValue) {
List<Object> targetList = new ArrayList<>();
for (Object it : listValue) {
targetList.add(preConvertNativeValues(it));
}
return targetList;
}

return value != null ? value : "";
}

/**
* {@link Converter} to convert {@link StreamReadOptions} to Lettuce's {@link XReadArgs}.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public ByteArrayWrapper(byte[] array) {
}

public boolean equals(@Nullable Object obj) {
if (obj instanceof ByteArrayWrapper byteArrayWrapper) {
return Arrays.equals(array, byteArrayWrapper.array);
if (obj instanceof ByteArrayWrapper other) {
return Arrays.equals(array, other.array);
}

return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,9 @@ protected void addKeyToIndex(byte[] key, IndexedData indexedData) {
return;
}

if (indexedData instanceof SimpleIndexedPropertyValue simpleIndexedData) {
if (indexedData instanceof SimpleIndexedPropertyValue propertyValue) {

Object value = simpleIndexedData.getValue();
Object value = propertyValue.getValue();

if (value == null) {
return;
Expand All @@ -222,15 +222,15 @@ protected void addKeyToIndex(byte[] key, IndexedData indexedData) {

// keep track of indexes used for the object
connection.sAdd(ByteUtils.concatAll(toBytes(indexedData.getKeyspace() + ":"), key, toBytes(":idx")), indexKey);
} else if (indexedData instanceof GeoIndexedPropertyValue geoIndexedData) {
} else if (indexedData instanceof GeoIndexedPropertyValue propertyValue) {

Object value = geoIndexedData.getValue();
Object value = propertyValue.getValue();
if (value == null) {
return;
}

byte[] indexKey = toBytes(indexedData.getKeyspace() + ":" + indexedData.getIndexName());
connection.geoAdd(indexKey, geoIndexedData.getPoint(), key);
connection.geoAdd(indexKey, propertyValue.getPoint(), key);

// keep track of indexes used for the object
connection.sAdd(ByteUtils.concatAll(toBytes(indexedData.getKeyspace() + ":"), key, toBytes(":idx")), indexKey);
Expand Down Expand Up @@ -264,7 +264,7 @@ private byte[] toBytes(@Nullable Object source) {
* @author Christoph Strobl
* @since 1.8
*/
private static enum IndexWriteMode {
private enum IndexWriteMode {

CREATE, UPDATE, PARTIAL_UPDATE
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.RawTargetAccess;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.dao.DataAccessException;
Expand Down Expand Up @@ -305,8 +304,8 @@ private static RedisConnection getTargetConnection(RedisConnection connection) {

RedisConnection connectionToUse = connection;

while (connectionToUse instanceof RedisConnectionProxy redisConnectionProxy) {
connectionToUse = redisConnectionProxy.getTargetConnection();
while (connectionToUse instanceof RedisConnectionProxy proxy) {
connectionToUse = proxy.getTargetConnection();
}

return connectionToUse;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ public Set<IndexedData> resolveIndexesFor(TypeInformation<?> typeInformation, @N

for (IndexDefinition setting : settings.getIndexDefinitionsFor(keyspace)) {

if (setting instanceof SpelIndexDefinition spelIndexDefinition) {
if (setting instanceof SpelIndexDefinition spel) {

Expression expression = getAndCacheIfAbsent(spelIndexDefinition);
Expression expression = getAndCacheIfAbsent(spel);

StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,8 @@ public E moveLastTo(RedisList<E> destination, RedisListCommands.Direction destin

@SuppressWarnings("unchecked")
private void potentiallyCap(RedisList<E> destination) {
if (destination instanceof DefaultRedisList<?> defaultRedisList) {
defaultRedisList.cap();
if (destination instanceof DefaultRedisList<?> redisList) {
redisList.cap();
}
}

Expand Down

0 comments on commit 667dd27

Please sign in to comment.