From 0abe602cf0d0a628b5cd427289c3506b76b27cd2 Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sat, 4 Jul 2026 05:40:33 +0900 Subject: [PATCH 1/2] fix(core): fix correctness/thread-safety/security bugs with regression tests Address review findings across core utilities while preserving backward compatibility. Behavior- and format-changing items (e.g. cipher default mode, UUID format, equals/hashCode contracts) are intentionally deferred. collection: - ArrayMap.clone() rebuilds buckets instead of truncating the hash table - LruHashSet/CaseInsensitiveSet implement writeObject/readObject - CaseInsensitiveMap handles null keys and lowercases with Locale.ROOT misc/lang: - DynamicProperties: fix reload throttle, delegate Map default methods, create parent directories with mkdirs() - SystemUtil/LocaleUtil use volatile suppliers; ClassUtil.newInstance uses getDeclaredConstructor(); StringUtil.replace guards empty search text io/nio/net: - FileUtil.readBytes reads until the buffer is filled or EOF - ChannelUtil loops transferTo until the whole source is copied - SerializeUtil default filter enforces depth/refs/bytes/array-length limits - Preserve a literal '+' when decoding URL/resource/jar/zip paths crypto/convert/beans/timer/xml/log/security: - CachedCipher re-initializes pooled ciphers per key; clears pool on config change - TimestampConversionUtil honors the locale; DecimalFormatSymbolsUtil returns a clone - BeanDescImpl no longer mutates caller args during method resolution; BeanDescFactory deregisters its cache disposable on clear() - TimeoutManager fixes the thread-clear race; TimeoutTask fields are volatile - SchemaFactoryUtil enables secure processing; Logger is null-safe Adds regression tests for the high-severity fixes. --- .../org/codelibs/core/CoreLibConstants.java | 3 +- .../core/beans/factory/BeanDescFactory.java | 7 +- .../core/beans/impl/BeanDescImpl.java | 27 ++- .../core/beans/impl/ConstructorDescImpl.java | 6 +- .../core/beans/impl/MethodDescImpl.java | 8 +- .../impl/ParameterizedClassDescImpl.java | 2 +- .../core/beans/impl/PropertyDescImpl.java | 2 +- .../codelibs/core/beans/util/CopyOptions.java | 2 +- .../core/collection/ArrayIterator.java | 1 + .../codelibs/core/collection/ArrayMap.java | 14 +- .../core/collection/CaseInsensitiveMap.java | 6 +- .../core/collection/CaseInsensitiveSet.java | 35 ++++ .../core/collection/IteratorEnumeration.java | 2 +- .../codelibs/core/collection/LruHashSet.java | 44 ++++- .../core/convert/BinaryConversionUtil.java | 4 +- .../core/convert/BooleanConversionUtil.java | 4 +- .../core/convert/TimestampConversionUtil.java | 3 +- .../codelibs/core/crypto/CachedCipher.java | 105 ++++++----- .../ClUnsupportedOperationException.java | 2 +- .../codelibs/core/io/ClassTraversalUtil.java | 6 +- .../java/org/codelibs/core/io/FileUtil.java | 20 +- .../core/io/ResourceTraversalUtil.java | 6 +- .../org/codelibs/core/io/ResourceUtil.java | 8 +- .../org/codelibs/core/io/SerializeUtil.java | 25 +++ .../org/codelibs/core/jar/JarFileUtil.java | 3 +- .../org/codelibs/core/lang/ClassUtil.java | 8 +- .../org/codelibs/core/lang/MethodUtil.java | 2 + .../org/codelibs/core/lang/StringUtil.java | 5 +- .../org/codelibs/core/lang/SystemUtil.java | 4 +- .../java/org/codelibs/core/log/Logger.java | 10 +- .../codelibs/core/misc/DynamicProperties.java | 68 ++++++- .../org/codelibs/core/misc/LocaleUtil.java | 8 +- .../org/codelibs/core/misc/ValueHolder.java | 2 +- .../org/codelibs/core/net/MimeTypeUtil.java | 5 +- .../java/org/codelibs/core/net/URLUtil.java | 4 +- .../org/codelibs/core/nio/ChannelUtil.java | 13 +- .../core/security/MessageDigestUtil.java | 9 +- .../core/text/DecimalFormatSymbolsUtil.java | 3 +- .../java/org/codelibs/core/text/JsonUtil.java | 2 +- .../org/codelibs/core/text/Tokenizer.java | 3 + .../codelibs/core/timer/TimeoutManager.java | 8 +- .../org/codelibs/core/timer/TimeoutTask.java | 4 +- .../codelibs/core/xml/SchemaFactoryUtil.java | 7 + .../org/codelibs/core/zip/ZipFileUtil.java | 3 +- .../core/beans/impl/BeanDescImplTest.java | 15 ++ .../core/collection/ArrayMapTest.java | 33 ++++ .../collection/CaseInsensitiveMapTest.java | 35 ++++ .../collection/CaseInsensitiveSetTest.java | 19 ++ .../core/collection/LruHashSetTest.java | 68 +++++++ .../convert/BinaryConversionUtilTest.java | 12 ++ .../convert/TimestampConversionUtilTest.java | 26 +++ .../core/crypto/CachedCipherTest.java | 40 ++++ .../org/codelibs/core/io/CopyUtilTest.java | 29 +++ .../org/codelibs/core/io/FileUtilTest.java | 22 +++ .../codelibs/core/io/SerializeUtilTest.java | 25 +++ .../org/codelibs/core/lang/ClassUtilTest.java | 38 ++++ .../codelibs/core/lang/StringUtilTest.java | 12 ++ .../core/misc/DynamicPropertiesTest.java | 171 ++++++++++++++++++ .../codelibs/core/misc/ValueHolderTest.java | 44 +++++ .../org/codelibs/core/net/URLUtilTest.java | 12 ++ .../text/DecimalFormatSymbolsUtilTest.java | 15 ++ .../org/codelibs/core/text/TokenizerTest.java | 11 ++ 62 files changed, 1024 insertions(+), 116 deletions(-) create mode 100644 src/test/java/org/codelibs/core/collection/LruHashSetTest.java create mode 100644 src/test/java/org/codelibs/core/misc/DynamicPropertiesTest.java create mode 100644 src/test/java/org/codelibs/core/misc/ValueHolderTest.java diff --git a/src/main/java/org/codelibs/core/CoreLibConstants.java b/src/main/java/org/codelibs/core/CoreLibConstants.java index eab6f19..c4be400 100644 --- a/src/main/java/org/codelibs/core/CoreLibConstants.java +++ b/src/main/java/org/codelibs/core/CoreLibConstants.java @@ -16,6 +16,7 @@ package org.codelibs.core; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** * Constants class. @@ -33,7 +34,7 @@ public class CoreLibConstants { /** * UTF-8 Charset. */ - public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); + public static final Charset CHARSET_UTF_8 = StandardCharsets.UTF_8; /** * ISO 8601 basic format: yyyyMMdd'T'HHmmss.SSSZ diff --git a/src/main/java/org/codelibs/core/beans/factory/BeanDescFactory.java b/src/main/java/org/codelibs/core/beans/factory/BeanDescFactory.java index e822a45..8444df6 100644 --- a/src/main/java/org/codelibs/core/beans/factory/BeanDescFactory.java +++ b/src/main/java/org/codelibs/core/beans/factory/BeanDescFactory.java @@ -23,6 +23,7 @@ import org.codelibs.core.beans.BeanDesc; import org.codelibs.core.beans.impl.BeanDescImpl; +import org.codelibs.core.misc.Disposable; import org.codelibs.core.misc.DisposableUtil; /** @@ -56,6 +57,9 @@ protected BeanDescFactory() { /** Cache of {@link BeanDesc} */ private static final ConcurrentMap, BeanDesc> beanDescCache = newConcurrentHashMap(1024); + /** Disposable that clears the cache; a single stable instance so it can be deregistered. */ + private static final Disposable DISPOSABLE = BeanDescFactory::clear; + static { initialize(); } @@ -86,7 +90,7 @@ public static BeanDesc getBeanDesc(final Class clazz) { public static void initialize() { synchronized (BeanDescFactory.class) { if (!initialized) { - DisposableUtil.add(BeanDescFactory::clear); + DisposableUtil.add(DISPOSABLE); initialized = true; } } @@ -97,6 +101,7 @@ public static void initialize() { */ public static void clear() { beanDescCache.clear(); + DisposableUtil.remove(DISPOSABLE); initialized = false; } diff --git a/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java b/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java index 3c56764..8f959fc 100644 --- a/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java +++ b/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java @@ -286,7 +286,7 @@ public MethodDesc[] getMethodDescs(final String methodName) { if (methodDescs == null) { throw new MethodNotFoundRuntimeException(beanClass, methodName, null); } - return methodDescs; + return methodDescs.clone(); } @Override @@ -404,18 +404,33 @@ protected boolean isSuitable(final Class[] paramTypes, final Object[] args, f if (paramTypes.length != args.length) { return false; } - for (int i = 0; i < args.length; ++i) { - if (args[i] == null) { + // When number adjustment is enabled, evaluate the match against a copy of the arguments. + // This prevents a partially-converted, non-matching candidate from polluting the evaluation + // of later candidates or leaving the caller's array modified, and lets a failed conversion be + // treated as a non-match instead of being propagated. The successful conversions are copied + // back to the caller's array only once a candidate has fully matched. + final Object[] work = adjustNumber ? args.clone() : args; + for (int i = 0; i < work.length; ++i) { + if (work[i] == null) { continue; } - if (ClassUtil.isAssignableFrom(paramTypes[i], args[i].getClass())) { + if (ClassUtil.isAssignableFrom(paramTypes[i], work[i].getClass())) { continue; } - if (adjustNumber && adjustNumber(paramTypes, args, i)) { - continue; + if (adjustNumber) { + try { + if (adjustNumber(paramTypes, work, i)) { + continue; + } + } catch (final RuntimeException e) { + return false; + } } return false; } + if (adjustNumber) { + System.arraycopy(work, 0, args, 0, args.length); + } return true; } diff --git a/src/main/java/org/codelibs/core/beans/impl/ConstructorDescImpl.java b/src/main/java/org/codelibs/core/beans/impl/ConstructorDescImpl.java index 135c23d..ed42d3d 100644 --- a/src/main/java/org/codelibs/core/beans/impl/ConstructorDescImpl.java +++ b/src/main/java/org/codelibs/core/beans/impl/ConstructorDescImpl.java @@ -84,7 +84,7 @@ public Constructor getConstructor() { @Override public Class[] getParameterTypes() { - return parameterTypes; + return parameterTypes.clone(); } @Override @@ -96,12 +96,12 @@ public boolean isPublic() { public boolean isParameterized(final int index) { assertArgumentArrayIndex("index", index, parameterTypes.length); - return parameterizedClassDescs[index].isParameterizedClass(); + return parameterizedClassDescs[index] != null && parameterizedClassDescs[index].isParameterizedClass(); } @Override public ParameterizedClassDesc[] getParameterizedClassDescs() { - return parameterizedClassDescs; + return parameterizedClassDescs.clone(); } @Override diff --git a/src/main/java/org/codelibs/core/beans/impl/MethodDescImpl.java b/src/main/java/org/codelibs/core/beans/impl/MethodDescImpl.java index 273f781..33da722 100644 --- a/src/main/java/org/codelibs/core/beans/impl/MethodDescImpl.java +++ b/src/main/java/org/codelibs/core/beans/impl/MethodDescImpl.java @@ -98,7 +98,7 @@ public String getMethodName() { @Override public Class[] getParameterTypes() { - return parameterTypes; + return parameterTypes.clone(); } @SuppressWarnings("unchecked") @@ -131,17 +131,17 @@ public boolean isAbstract() { public boolean isParameterized(final int index) { assertArgumentArrayIndex("index", index, parameterTypes.length); - return parameterizedClassDescs[index].isParameterizedClass(); + return parameterizedClassDescs[index] != null && parameterizedClassDescs[index].isParameterizedClass(); } @Override public boolean isParameterized() { - return parameterizedClassDesc.isParameterizedClass(); + return parameterizedClassDesc != null && parameterizedClassDesc.isParameterizedClass(); } @Override public ParameterizedClassDesc[] getParameterizedClassDescs() { - return parameterizedClassDescs; + return parameterizedClassDescs.clone(); } @Override diff --git a/src/main/java/org/codelibs/core/beans/impl/ParameterizedClassDescImpl.java b/src/main/java/org/codelibs/core/beans/impl/ParameterizedClassDescImpl.java index b154c3e..d94b4b9 100644 --- a/src/main/java/org/codelibs/core/beans/impl/ParameterizedClassDescImpl.java +++ b/src/main/java/org/codelibs/core/beans/impl/ParameterizedClassDescImpl.java @@ -84,7 +84,7 @@ public void setRawClass(final Class rawClass) { @Override public ParameterizedClassDesc[] getArguments() { - return arguments; + return arguments == null ? null : arguments.clone(); } /** diff --git a/src/main/java/org/codelibs/core/beans/impl/PropertyDescImpl.java b/src/main/java/org/codelibs/core/beans/impl/PropertyDescImpl.java index 8033ae5..a6db784 100644 --- a/src/main/java/org/codelibs/core/beans/impl/PropertyDescImpl.java +++ b/src/main/java/org/codelibs/core/beans/impl/PropertyDescImpl.java @@ -154,7 +154,7 @@ private void setupValueOfMethod() { } private void setUpParameterizedClassDesc() { - final Map, Type> typeVariables = ((BeanDescImpl) beanDesc).getTypeVariables(); + final Map, Type> typeVariables = beanDesc.getTypeVariables(); if (field != null) { parameterizedClassDesc = ParameterizedClassDescFactory.createParameterizedClassDesc(field, typeVariables); } else if (readMethod != null) { diff --git a/src/main/java/org/codelibs/core/beans/util/CopyOptions.java b/src/main/java/org/codelibs/core/beans/util/CopyOptions.java index b468e8e..70bd7d6 100644 --- a/src/main/java/org/codelibs/core/beans/util/CopyOptions.java +++ b/src/main/java/org/codelibs/core/beans/util/CopyOptions.java @@ -170,7 +170,7 @@ public CopyOptions excludeWhitespace() { * @return This instance itself */ public CopyOptions prefix(final CharSequence prefix) { - assertArgumentNotEmpty("propertyNames", prefix); + assertArgumentNotEmpty("prefix", prefix); this.prefix = prefix.toString(); return this; diff --git a/src/main/java/org/codelibs/core/collection/ArrayIterator.java b/src/main/java/org/codelibs/core/collection/ArrayIterator.java index b0bfea9..7f747ca 100644 --- a/src/main/java/org/codelibs/core/collection/ArrayIterator.java +++ b/src/main/java/org/codelibs/core/collection/ArrayIterator.java @@ -67,6 +67,7 @@ public static Iterable iterable(final T... items) { * @param items the array of elements to iterate (must not be {@literal null}) */ public ArrayIterator(final T... items) { + assertArgumentNotNull("items", items); this.items = items; } diff --git a/src/main/java/org/codelibs/core/collection/ArrayMap.java b/src/main/java/org/codelibs/core/collection/ArrayMap.java index 62b8839..15e9de8 100644 --- a/src/main/java/org/codelibs/core/collection/ArrayMap.java +++ b/src/main/java/org/codelibs/core/collection/ArrayMap.java @@ -25,7 +25,6 @@ import java.lang.reflect.Array; import java.util.AbstractMap; import java.util.AbstractSet; -import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; @@ -371,6 +370,9 @@ public Iterator> iterator() { @Override public boolean contains(final Object o) { + if (!(o instanceof Entry)) { + return false; + } final Entry entry = (Entry) o; final int index = (entry.hashCode & 0x7FFFFFFF) % mapTable.length; for (Entry e = mapTable[index]; e != null; e = e.next) { @@ -431,11 +433,11 @@ public void readExternal(final ObjectInput in) throws IOException, ClassNotFound @Override public Object clone() { - final ArrayMap copy = new ArrayMap<>(); - copy.threshold = threshold; - copy.mapTable = Arrays.copyOf(mapTable, size); - copy.listTable = Arrays.copyOf(listTable, size); - copy.size = size; + final ArrayMap copy = new ArrayMap<>(mapTable.length); + for (int i = 0; i < size; i++) { + final Entry entry = listTable[i]; + copy.put(entry.key, entry.value); + } return copy; } diff --git a/src/main/java/org/codelibs/core/collection/CaseInsensitiveMap.java b/src/main/java/org/codelibs/core/collection/CaseInsensitiveMap.java index 215f679..19fb614 100644 --- a/src/main/java/org/codelibs/core/collection/CaseInsensitiveMap.java +++ b/src/main/java/org/codelibs/core/collection/CaseInsensitiveMap.java @@ -15,6 +15,7 @@ */ package org.codelibs.core.collection; +import java.util.Locale; import java.util.Map; /** @@ -80,7 +81,10 @@ public boolean containsKey(final Object key) { } private static String convertKey(final Object key) { - return key.toString().toLowerCase(); + if (key == null) { + return null; + } + return key.toString().toLowerCase(Locale.ROOT); } } diff --git a/src/main/java/org/codelibs/core/collection/CaseInsensitiveSet.java b/src/main/java/org/codelibs/core/collection/CaseInsensitiveSet.java index dfc21ba..96dea4d 100644 --- a/src/main/java/org/codelibs/core/collection/CaseInsensitiveSet.java +++ b/src/main/java/org/codelibs/core/collection/CaseInsensitiveSet.java @@ -15,6 +15,9 @@ */ package org.codelibs.core.collection; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractSet; import java.util.Collection; @@ -96,4 +99,36 @@ public void clear() { map.clear(); } + /** + * Serializes this set. The backing map is {@code transient} and its values are a + * non-serializable sentinel, so only the elements are written. + * + * @param s the stream to write to + * @throws IOException if an I/O error occurs + */ + private void writeObject(final ObjectOutputStream s) throws IOException { + s.defaultWriteObject(); + s.writeInt(map.size()); + for (final String e : map.keySet()) { + s.writeObject(e); + } + } + + /** + * Deserializes this set by rebuilding the backing map from the elements written by + * {@link #writeObject(ObjectOutputStream)}. + * + * @param s the stream to read from + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if the class of a serialized element cannot be found + */ + private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { + s.defaultReadObject(); + map = new CaseInsensitiveMap<>(); + final int size = s.readInt(); + for (int i = 0; i < size; i++) { + map.put((String) s.readObject(), PRESENT); + } + } + } diff --git a/src/main/java/org/codelibs/core/collection/IteratorEnumeration.java b/src/main/java/org/codelibs/core/collection/IteratorEnumeration.java index aa1a472..df41d4a 100644 --- a/src/main/java/org/codelibs/core/collection/IteratorEnumeration.java +++ b/src/main/java/org/codelibs/core/collection/IteratorEnumeration.java @@ -28,7 +28,7 @@ */ public class IteratorEnumeration implements Enumeration { - /** 反復子 */ + /** The iterator */ protected final Iterator iterator; /** diff --git a/src/main/java/org/codelibs/core/collection/LruHashSet.java b/src/main/java/org/codelibs/core/collection/LruHashSet.java index 80227d8..f7207e5 100644 --- a/src/main/java/org/codelibs/core/collection/LruHashSet.java +++ b/src/main/java/org/codelibs/core/collection/LruHashSet.java @@ -15,6 +15,10 @@ */ package org.codelibs.core.collection; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; import java.util.AbstractSet; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -29,13 +33,13 @@ * @author shinsuke * @param the type of elements maintained by this set */ -public class LruHashSet extends AbstractSet implements Set, java.io.Serializable { +public class LruHashSet extends AbstractSet implements Set, Serializable { private static final long serialVersionUID = 1L; /** * The internal LRU hash map used to store elements. */ - private final LruHashMap map; + private transient LruHashMap map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); @@ -127,4 +131,40 @@ public void clear() { map.clear(); } + /** + * Serializes this set. The backing map is {@code transient} and its values are a + * non-serializable sentinel, so only the limit size and the elements are written. + * + * @param s the stream to write to + * @throws IOException if an I/O error occurs + */ + private void writeObject(final ObjectOutputStream s) throws IOException { + s.defaultWriteObject(); + s.writeInt(map.getLimitSize()); + s.writeInt(map.size()); + for (final E e : map.keySet()) { + s.writeObject(e); + } + } + + /** + * Deserializes this set by rebuilding the backing map from the limit size and the + * elements written by {@link #writeObject(ObjectOutputStream)}. + * + * @param s the stream to read from + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if the class of a serialized element cannot be found + */ + private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { + s.defaultReadObject(); + final int limitSize = s.readInt(); + map = new LruHashMap<>(limitSize); + final int size = s.readInt(); + for (int i = 0; i < size; i++) { + @SuppressWarnings("unchecked") + final E e = (E) s.readObject(); + map.put(e, PRESENT); + } + } + } diff --git a/src/main/java/org/codelibs/core/convert/BinaryConversionUtil.java b/src/main/java/org/codelibs/core/convert/BinaryConversionUtil.java index 0d8a16e..4986e27 100644 --- a/src/main/java/org/codelibs/core/convert/BinaryConversionUtil.java +++ b/src/main/java/org/codelibs/core/convert/BinaryConversionUtil.java @@ -17,6 +17,8 @@ import static org.codelibs.core.misc.AssertionUtil.assertArgument; +import java.nio.charset.StandardCharsets; + /** * Utility class for conversions related to byte arrays. * @@ -44,7 +46,7 @@ public static byte[] toBinary(final Object o) { return null; } else { assertArgument("o", o instanceof String, o.getClass().toString()); - return ((String) o).getBytes(); + return ((String) o).getBytes(StandardCharsets.UTF_8); } } diff --git a/src/main/java/org/codelibs/core/convert/BooleanConversionUtil.java b/src/main/java/org/codelibs/core/convert/BooleanConversionUtil.java index ca0d03a..c06315c 100644 --- a/src/main/java/org/codelibs/core/convert/BooleanConversionUtil.java +++ b/src/main/java/org/codelibs/core/convert/BooleanConversionUtil.java @@ -15,6 +15,8 @@ */ package org.codelibs.core.convert; +import java.util.Locale; + /** * Utility class for conversions related to {@link Boolean}. * @@ -40,7 +42,7 @@ public static Boolean toBoolean(final Object o) { case null -> null; case Boolean b -> b; case Number n -> n.intValue() != 0; - case String s -> switch (s.toLowerCase()) { + case String s -> switch (s.toLowerCase(Locale.ROOT)) { case "true" -> Boolean.TRUE; case "false", "0" -> Boolean.FALSE; default -> Boolean.TRUE; diff --git a/src/main/java/org/codelibs/core/convert/TimestampConversionUtil.java b/src/main/java/org/codelibs/core/convert/TimestampConversionUtil.java index 20e21f4..ee4fd82 100644 --- a/src/main/java/org/codelibs/core/convert/TimestampConversionUtil.java +++ b/src/main/java/org/codelibs/core/convert/TimestampConversionUtil.java @@ -151,6 +151,7 @@ public static String getLongPattern() { * @return the pattern string for {@link DateFormat#LONG} style */ public static String getLongPattern(final Locale locale) { + assertArgumentNotNull("locale", locale); return ((SimpleDateFormat) getDateTimeInstance(LONG, LONG, locale)).toPattern(); } @@ -323,7 +324,7 @@ protected static Calendar toCalendar(final Object src, final String pattern, fin return null; } if (isNotEmpty(pattern)) { - final SimpleDateFormat format = new SimpleDateFormat(pattern); + final SimpleDateFormat format = new SimpleDateFormat(pattern, locale); final Date date = toDate(str, format); if (date != null) { return toCalendar(date, locale); diff --git a/src/main/java/org/codelibs/core/crypto/CachedCipher.java b/src/main/java/org/codelibs/core/crypto/CachedCipher.java index 7c31640..fcd561a 100644 --- a/src/main/java/org/codelibs/core/crypto/CachedCipher.java +++ b/src/main/java/org/codelibs/core/crypto/CachedCipher.java @@ -342,20 +342,21 @@ public String decryptoText(final String text) { */ protected Cipher pollEncryptoCipher() { Cipher cipher = encryptoQueue.poll(); - if (cipher == null) { - try { - final SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(charsetName), algorithm); + try { + if (cipher == null) { cipher = Cipher.getInstance(algorithm); - cipher.init(Cipher.ENCRYPT_MODE, sksSpec); - } catch (final InvalidKeyException e) { - throw new InvalidKeyRuntimeException(e); - } catch (final NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmRuntimeException(e); - } catch (final NoSuchPaddingException e) { - throw new NoSuchPaddingRuntimeException(e); - } catch (final UnsupportedEncodingException e) { - throw new UnsupportedEncodingRuntimeException(e); } + // Always (re-)initialize so a pooled cipher never retains a stale key. + final SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(charsetName), algorithm); + cipher.init(Cipher.ENCRYPT_MODE, sksSpec); + } catch (final InvalidKeyException e) { + throw new InvalidKeyRuntimeException(e); + } catch (final NoSuchAlgorithmException e) { + throw new NoSuchAlgorithmRuntimeException(e); + } catch (final NoSuchPaddingException e) { + throw new NoSuchPaddingRuntimeException(e); + } catch (final UnsupportedEncodingException e) { + throw new UnsupportedEncodingRuntimeException(e); } return cipher; } @@ -369,17 +370,18 @@ protected Cipher pollEncryptoCipher() { */ protected Cipher pollEncryptoCipher(final Key key) { Cipher cipher = encryptoQueue.poll(); - if (cipher == null) { - try { + try { + if (cipher == null) { cipher = Cipher.getInstance(transformation); - cipher.init(Cipher.ENCRYPT_MODE, key); - } catch (final InvalidKeyException e) { - throw new InvalidKeyRuntimeException(e); - } catch (final NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmRuntimeException(e); - } catch (final NoSuchPaddingException e) { - throw new NoSuchPaddingRuntimeException(e); } + // Always (re-)initialize with the given key; a pooled cipher may hold a different key. + cipher.init(Cipher.ENCRYPT_MODE, key); + } catch (final InvalidKeyException e) { + throw new InvalidKeyRuntimeException(e); + } catch (final NoSuchAlgorithmException e) { + throw new NoSuchAlgorithmRuntimeException(e); + } catch (final NoSuchPaddingException e) { + throw new NoSuchPaddingRuntimeException(e); } return cipher; } @@ -401,20 +403,21 @@ protected void offerEncryptoCipher(final Cipher cipher) { */ protected Cipher pollDecryptoCipher() { Cipher cipher = decryptoQueue.poll(); - if (cipher == null) { - try { - final SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(charsetName), algorithm); + try { + if (cipher == null) { cipher = Cipher.getInstance(algorithm); - cipher.init(Cipher.DECRYPT_MODE, sksSpec); - } catch (final InvalidKeyException e) { - throw new InvalidKeyRuntimeException(e); - } catch (final NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmRuntimeException(e); - } catch (final NoSuchPaddingException e) { - throw new NoSuchPaddingRuntimeException(e); - } catch (final UnsupportedEncodingException e) { - throw new UnsupportedEncodingRuntimeException(e); } + // Always (re-)initialize so a pooled cipher never retains a stale key. + final SecretKeySpec sksSpec = new SecretKeySpec(key.getBytes(charsetName), algorithm); + cipher.init(Cipher.DECRYPT_MODE, sksSpec); + } catch (final InvalidKeyException e) { + throw new InvalidKeyRuntimeException(e); + } catch (final NoSuchAlgorithmException e) { + throw new NoSuchAlgorithmRuntimeException(e); + } catch (final NoSuchPaddingException e) { + throw new NoSuchPaddingRuntimeException(e); + } catch (final UnsupportedEncodingException e) { + throw new UnsupportedEncodingRuntimeException(e); } return cipher; } @@ -428,17 +431,18 @@ protected Cipher pollDecryptoCipher() { */ protected Cipher pollDecryptoCipher(final Key key) { Cipher cipher = decryptoQueue.poll(); - if (cipher == null) { - try { + try { + if (cipher == null) { cipher = Cipher.getInstance(transformation); - cipher.init(Cipher.DECRYPT_MODE, key); - } catch (final InvalidKeyException e) { - throw new InvalidKeyRuntimeException(e); - } catch (final NoSuchAlgorithmException e) { - throw new NoSuchAlgorithmRuntimeException(e); - } catch (final NoSuchPaddingException e) { - throw new NoSuchPaddingRuntimeException(e); } + // Always (re-)initialize with the given key; a pooled cipher may hold a different key. + cipher.init(Cipher.DECRYPT_MODE, key); + } catch (final InvalidKeyException e) { + throw new InvalidKeyRuntimeException(e); + } catch (final NoSuchAlgorithmException e) { + throw new NoSuchAlgorithmRuntimeException(e); + } catch (final NoSuchPaddingException e) { + throw new NoSuchPaddingRuntimeException(e); } return cipher; } @@ -453,6 +457,21 @@ protected void offerDecryptoCipher(final Cipher cipher) { decryptoQueue.offer(cipher); } + /** + * Discards all pooled ciphers so that subsequent operations rebuild them with the + * current algorithm/transformation. + *

+ * This is required when the algorithm or transformation changes because those values + * are fixed on a {@link Cipher} instance at creation time and cannot be changed by + * re-initialization. Configuration setters are expected to be called before concurrent + * use. + *

+ */ + protected void clearCipherQueues() { + encryptoQueue.clear(); + decryptoQueue.clear(); + } + /** * Returns the algorithm. * @@ -470,6 +489,7 @@ public String getAlgorithm() { */ public void setAlgorithm(final String algorithm) { this.algorithm = algorithm; + clearCipherQueues(); } /** @@ -489,6 +509,7 @@ public String getTransformation() { */ public void setTransformation(final String transformation) { this.transformation = transformation; + clearCipherQueues(); } /** diff --git a/src/main/java/org/codelibs/core/exception/ClUnsupportedOperationException.java b/src/main/java/org/codelibs/core/exception/ClUnsupportedOperationException.java index 9f2289f..a21fd35 100644 --- a/src/main/java/org/codelibs/core/exception/ClUnsupportedOperationException.java +++ b/src/main/java/org/codelibs/core/exception/ClUnsupportedOperationException.java @@ -5,7 +5,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/src/main/java/org/codelibs/core/io/ClassTraversalUtil.java b/src/main/java/org/codelibs/core/io/ClassTraversalUtil.java index b959ae7..d2846d8 100644 --- a/src/main/java/org/codelibs/core/io/ClassTraversalUtil.java +++ b/src/main/java/org/codelibs/core/io/ClassTraversalUtil.java @@ -191,7 +191,11 @@ public static void forEach(final ZipInputStream zipInputStream, final String pre * @param handler the handler to process classes */ protected static void traverseFileSystem(final File dir, final String packageName, final ClassHandler handler) { - for (final File file : dir.listFiles()) { + final File[] files = dir.listFiles(); + if (files == null) { + return; + } + for (final File file : files) { final String fileName = file.getName(); if (file.isDirectory()) { traverseFileSystem(file, ClassUtil.concatName(packageName, fileName), handler); diff --git a/src/main/java/org/codelibs/core/io/FileUtil.java b/src/main/java/org/codelibs/core/io/FileUtil.java index 3198f78..5e250d7 100644 --- a/src/main/java/org/codelibs/core/io/FileUtil.java +++ b/src/main/java/org/codelibs/core/io/FileUtil.java @@ -81,6 +81,14 @@ protected FileUtil() { * throw new SecurityException("Path traversal attempt detected"); * } * + *

+ * Note: This method performs purely lexical normalization via + * {@link Path#normalize()} and does not resolve symbolic links. A symbolic + * link located inside {@code baseDirectory} that points outside of it is therefore + * still considered safe. If symbolic-link resolution is required, resolve both paths + * with {@link Path#toRealPath(java.nio.file.LinkOption...)} before calling this method + * (note that {@code toRealPath} requires the paths to exist). + *

* * @param pathToCheck the path to validate (must not be {@literal null}) * @param baseDirectory the base directory that the path must be within (must not be {@literal null}) @@ -190,9 +198,19 @@ public static byte[] readBytes(final File file, final long maxSize) { throw new IORuntimeException(new IOException( "File too large: " + fileSize + " bytes (max: " + maxSize + " bytes). Use streaming APIs for large files.")); } + if (fileSize > Integer.MAX_VALUE) { + throw new IORuntimeException(new IOException("File too large: " + fileSize + " bytes (max: " + Integer.MAX_VALUE + + " bytes for a byte array). Use streaming APIs for large files.")); + } final ByteBuffer buffer = ByteBuffer.allocate((int) fileSize); - ChannelUtil.read(channel, buffer); + // FileChannel.read may return before the buffer is filled, so keep + // reading until the buffer is full or the end of the file is reached. + while (buffer.hasRemaining()) { + if (ChannelUtil.read(channel, buffer) == -1) { + break; + } + } return buffer.array(); } finally { CloseableUtil.close(is); diff --git a/src/main/java/org/codelibs/core/io/ResourceTraversalUtil.java b/src/main/java/org/codelibs/core/io/ResourceTraversalUtil.java index 481fdf2..e4d0403 100644 --- a/src/main/java/org/codelibs/core/io/ResourceTraversalUtil.java +++ b/src/main/java/org/codelibs/core/io/ResourceTraversalUtil.java @@ -198,7 +198,11 @@ public void close() throws IOException { * the handler to process resources */ protected static void traverseFileSystem(final File rootDir, final File baseDir, final ResourceHandler handler) { - for (final File file : baseDir.listFiles()) { + final File[] files = baseDir.listFiles(); + if (files == null) { + return; + } + for (final File file : files) { if (file.isDirectory()) { traverseFileSystem(rootDir, file, handler); } else { diff --git a/src/main/java/org/codelibs/core/io/ResourceUtil.java b/src/main/java/org/codelibs/core/io/ResourceUtil.java index daa2cd8..11939bb 100644 --- a/src/main/java/org/codelibs/core/io/ResourceUtil.java +++ b/src/main/java/org/codelibs/core/io/ResourceUtil.java @@ -361,7 +361,8 @@ public static String toExternalForm(final URL url) { assertArgumentNotNull("url", url); final String s = url.toExternalForm(); - return URLUtil.decode(s, "UTF8"); + // Preserve a literal '+' in the path (URLUtil.decode would turn it into a space). + return URLUtil.decode(s.replace("+", "%2B"), "UTF8"); } /** @@ -375,7 +376,8 @@ public static String getFileName(final URL url) { assertArgumentNotNull("url", url); final String s = url.getFile(); - return URLUtil.decode(s, "UTF8"); + // Preserve a literal '+' in the path (URLUtil.decode would turn it into a space). + return URLUtil.decode(s.replace("+", "%2B"), "UTF8"); } /** @@ -389,7 +391,7 @@ public static File getFile(final URL url) { assertArgumentNotNull("url", url); final File file = new File(getFileName(url)); - if (file != null && file.exists()) { + if (file.exists()) { return file; } return null; diff --git a/src/main/java/org/codelibs/core/io/SerializeUtil.java b/src/main/java/org/codelibs/core/io/SerializeUtil.java index 844efd1..60159da 100644 --- a/src/main/java/org/codelibs/core/io/SerializeUtil.java +++ b/src/main/java/org/codelibs/core/io/SerializeUtil.java @@ -54,6 +54,18 @@ protected SerializeUtil() { private static final int BYTE_ARRAY_SIZE = 8 * 1024; + /** Maximum object graph depth allowed by the default filter. */ + private static final long MAX_DEPTH = 100L; + + /** Maximum number of object references allowed by the default filter. */ + private static final long MAX_REFERENCES = 1_000_000L; + + /** Maximum number of stream bytes allowed by the default filter. */ + private static final long MAX_STREAM_BYTES = 100L * 1024L * 1024L; + + /** Maximum array length allowed by the default filter. */ + private static final long MAX_ARRAY_LENGTH = 1_000_000L; + /** * Default set of allowed class name patterns for deserialization. * This helps prevent deserialization attacks by restricting which classes can be instantiated. @@ -64,9 +76,22 @@ protected SerializeUtil() { /** * Default ObjectInputFilter that only allows safe classes to be deserialized. + *

+ * In addition to the class allowlist, this filter enforces resource limits + * ({@link #MAX_DEPTH}, {@link #MAX_REFERENCES}, {@link #MAX_STREAM_BYTES}, + * {@link #MAX_ARRAY_LENGTH}) so that a payload composed solely of allowed + * classes cannot exhaust memory or CPU during deserialization. + *

* This filter rejects potentially dangerous classes while allowing common safe types. */ private static final ObjectInputFilter DEFAULT_FILTER = filterInfo -> { + // Defense-in-depth: reject payloads that exceed resource limits even when + // every class in the payload is otherwise allowed. + if (filterInfo.depth() > MAX_DEPTH || filterInfo.references() > MAX_REFERENCES || filterInfo.streamBytes() > MAX_STREAM_BYTES + || filterInfo.arrayLength() > MAX_ARRAY_LENGTH) { + return ObjectInputFilter.Status.REJECTED; + } + final Class serialClass = filterInfo.serialClass(); if (serialClass == null) { return ObjectInputFilter.Status.UNDECIDED; diff --git a/src/main/java/org/codelibs/core/jar/JarFileUtil.java b/src/main/java/org/codelibs/core/jar/JarFileUtil.java index 7d20e5e..f7bc157 100644 --- a/src/main/java/org/codelibs/core/jar/JarFileUtil.java +++ b/src/main/java/org/codelibs/core/jar/JarFileUtil.java @@ -127,7 +127,8 @@ public static String toJarFilePath(final URL jarUrl) { final String nestedUrlPath = nestedUrl.getPath(); final int pos = nestedUrlPath.lastIndexOf('!'); final String jarFilePath = nestedUrlPath.substring(0, pos); - final File jarFile = new File(URLUtil.decode(jarFilePath, "UTF8")); + // Preserve a literal '+' in the path (URLUtil.decode would turn it into a space). + final File jarFile = new File(URLUtil.decode(jarFilePath.replace("+", "%2B"), "UTF8")); return FileUtil.getCanonicalPath(jarFile); } diff --git a/src/main/java/org/codelibs/core/lang/ClassUtil.java b/src/main/java/org/codelibs/core/lang/ClassUtil.java index 3402515..df03778 100644 --- a/src/main/java/org/codelibs/core/lang/ClassUtil.java +++ b/src/main/java/org/codelibs/core/lang/ClassUtil.java @@ -21,6 +21,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; @@ -28,6 +29,7 @@ import org.codelibs.core.exception.EmptyArgumentException; import org.codelibs.core.exception.IllegalAccessRuntimeException; import org.codelibs.core.exception.InstantiationRuntimeException; +import org.codelibs.core.exception.InvocationTargetRuntimeException; import org.codelibs.core.exception.NoSuchConstructorRuntimeException; import org.codelibs.core.exception.NoSuchFieldRuntimeException; import org.codelibs.core.exception.NoSuchMethodRuntimeException; @@ -216,11 +218,15 @@ public static T newInstance(final Class clazz) throws InstantiationRuntim assertArgumentNotNull("clazz", clazz); try { - return clazz.newInstance(); + return clazz.getDeclaredConstructor().newInstance(); } catch (final InstantiationException e) { throw new InstantiationRuntimeException(clazz, e); } catch (final IllegalAccessException e) { throw new IllegalAccessRuntimeException(clazz, e); + } catch (final InvocationTargetException e) { + throw new InvocationTargetRuntimeException(clazz, e); + } catch (final NoSuchMethodException e) { + throw new NoSuchConstructorRuntimeException(clazz, new Class[0], e); } } diff --git a/src/main/java/org/codelibs/core/lang/MethodUtil.java b/src/main/java/org/codelibs/core/lang/MethodUtil.java index c8dfdba..b7113c6 100644 --- a/src/main/java/org/codelibs/core/lang/MethodUtil.java +++ b/src/main/java/org/codelibs/core/lang/MethodUtil.java @@ -110,6 +110,8 @@ public static T invokeStatic(final Method method, final Object... args) * @return abstract if the method is abstract */ public static boolean isAbstract(final Method method) { + assertArgumentNotNull("method", method); + return Modifier.isAbstract(method.getModifiers()); } diff --git a/src/main/java/org/codelibs/core/lang/StringUtil.java b/src/main/java/org/codelibs/core/lang/StringUtil.java index 91ab09d..e2e8bd8 100644 --- a/src/main/java/org/codelibs/core/lang/StringUtil.java +++ b/src/main/java/org/codelibs/core/lang/StringUtil.java @@ -38,7 +38,7 @@ protected StringUtil() { /** * A system line separator. */ - public static final String RETURN_STRING = System.getProperty("line.separator"); + public static final String RETURN_STRING = System.lineSeparator(); /** * An empty string "". @@ -85,6 +85,9 @@ public static final String replace(final String text, final String fromText, fin if (text == null || fromText == null || toText == null) { return null; } + if (fromText.isEmpty()) { + return text; + } final StringBuilder buf = new StringBuilder(100); int pos = 0; int pos2 = 0; diff --git a/src/main/java/org/codelibs/core/lang/SystemUtil.java b/src/main/java/org/codelibs/core/lang/SystemUtil.java index 89ce26e..5a86186 100644 --- a/src/main/java/org/codelibs/core/lang/SystemUtil.java +++ b/src/main/java/org/codelibs/core/lang/SystemUtil.java @@ -40,7 +40,7 @@ protected SystemUtil() { /** * line.separator system property. For example, on Mac OS X: "\n" */ - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); + public static final String LINE_SEPARATOR = System.lineSeparator(); /** * path.separator system property. For example, on Mac OS X: ":" @@ -112,7 +112,7 @@ public static String getEnv(String key, String defaultValue) { /** * Provider for current time in milliseconds. Can be overridden for testing. */ - private static LongSupplier timeProvider = System::currentTimeMillis; + private static volatile LongSupplier timeProvider = System::currentTimeMillis; /** * Returns the current time in milliseconds. diff --git a/src/main/java/org/codelibs/core/log/Logger.java b/src/main/java/org/codelibs/core/log/Logger.java index 9206ab2..9030dba 100644 --- a/src/main/java/org/codelibs/core/log/Logger.java +++ b/src/main/java/org/codelibs/core/log/Logger.java @@ -274,7 +274,7 @@ public void warn(final Object message, final Throwable throwable) { * Message */ public void warn(final Object message) { - log.warn(message.toString()); + log.warn(toString(message)); } /** @@ -286,7 +286,7 @@ public void warn(final Object message) { * Exception */ public void error(final Object message, final Throwable throwable) { - log.error(message.toString(), throwable); + log.error(toString(message), throwable); } /** @@ -296,7 +296,7 @@ public void error(final Object message, final Throwable throwable) { * Message */ public void error(final Object message) { - log.error(message.toString()); + log.error(toString(message)); } /** @@ -308,7 +308,7 @@ public void error(final Object message) { * Exception */ public void fatal(final Object message, final Throwable throwable) { - log.fatal(message.toString(), throwable); + log.fatal(toString(message), throwable); } /** @@ -318,7 +318,7 @@ public void fatal(final Object message, final Throwable throwable) { * Message */ public void fatal(final Object message) { - log.fatal(message.toString()); + log.fatal(toString(message)); } /** diff --git a/src/main/java/org/codelibs/core/misc/DynamicProperties.java b/src/main/java/org/codelibs/core/misc/DynamicProperties.java index fb86ba0..3d8b325 100644 --- a/src/main/java/org/codelibs/core/misc/DynamicProperties.java +++ b/src/main/java/org/codelibs/core/misc/DynamicProperties.java @@ -32,6 +32,9 @@ import java.util.Map; import java.util.Properties; import java.util.Set; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; import org.codelibs.core.exception.FileAccessException; import org.codelibs.core.exception.IORuntimeException; @@ -138,9 +141,9 @@ public DynamicProperties(final File file) { this.propertiesFile = file; if (!this.propertiesFile.exists()) { - final File parentDir = this.propertiesFile.getParentFile(); + final File parentDir = this.propertiesFile.getAbsoluteFile().getParentFile(); if (!parentDir.exists()) { - if (!parentDir.mkdir()) { + if (!parentDir.mkdirs()) { throw new FileAccessException("ECL0109", new Object[] { file.getAbsolutePath() }); } } else if (!parentDir.isDirectory()) { @@ -165,9 +168,9 @@ public DynamicProperties(final File file) { public synchronized void reload(final String path) { final File file = new File(path); if (!file.exists()) { - final File parentDir = file.getParentFile(); + final File parentDir = file.getAbsoluteFile().getParentFile(); if (!parentDir.exists()) { - if (!parentDir.mkdir()) { + if (!parentDir.mkdirs()) { throw new FileAccessException("ECL0109", new Object[] { path }); } } else if (!parentDir.isDirectory()) { @@ -191,7 +194,6 @@ public synchronized void reload(final String path) { public boolean isUpdated() { final long now = System.currentTimeMillis(); if (now - lastChecked < checkInterval) { - lastChecked = now; return false; } lastChecked = now; @@ -433,6 +435,62 @@ public Collection values() { return getProperties().values(); } + @Override + public Object getOrDefault(final Object key, final Object defaultValue) { + return getProperties().getOrDefault(key, defaultValue); + } + + @Override + public void forEach(final BiConsumer action) { + getProperties().forEach(action); + } + + @Override + public void replaceAll(final BiFunction function) { + getProperties().replaceAll(function); + } + + @Override + public Object putIfAbsent(final Object key, final Object value) { + return getProperties().putIfAbsent(key, value); + } + + @Override + public boolean remove(final Object key, final Object value) { + return getProperties().remove(key, value); + } + + @Override + public boolean replace(final Object key, final Object oldValue, final Object newValue) { + return getProperties().replace(key, oldValue, newValue); + } + + @Override + public Object replace(final Object key, final Object value) { + return getProperties().replace(key, value); + } + + @Override + public Object computeIfAbsent(final Object key, final Function mappingFunction) { + return getProperties().computeIfAbsent(key, mappingFunction); + } + + @Override + public Object computeIfPresent(final Object key, final BiFunction remappingFunction) { + return getProperties().computeIfPresent(key, remappingFunction); + } + + @Override + public Object compute(final Object key, final BiFunction remappingFunction) { + return getProperties().compute(key, remappingFunction); + } + + @Override + public Object merge(final Object key, final Object value, + final BiFunction remappingFunction) { + return getProperties().merge(key, value, remappingFunction); + } + /** * Sets the check interval for file modifications. * diff --git a/src/main/java/org/codelibs/core/misc/LocaleUtil.java b/src/main/java/org/codelibs/core/misc/LocaleUtil.java index 7dc92db..55dc221 100644 --- a/src/main/java/org/codelibs/core/misc/LocaleUtil.java +++ b/src/main/java/org/codelibs/core/misc/LocaleUtil.java @@ -49,17 +49,17 @@ public static Locale getLocale(final String localeStr) { switch (parts.length) { case 1: - return new Locale(parts[0]); + return Locale.of(parts[0]); case 2: - return new Locale(parts[0], parts[1]); + return Locale.of(parts[0], parts[1]); case 3: - return new Locale(parts[0], parts[1], parts[2]); + return Locale.of(parts[0], parts[1], parts[2]); default: return LocaleUtil.getDefault(); } } - private static Supplier defaultLocaleSupplier; + private static volatile Supplier defaultLocaleSupplier; /** * Returns the default locale. diff --git a/src/main/java/org/codelibs/core/misc/ValueHolder.java b/src/main/java/org/codelibs/core/misc/ValueHolder.java index 9b3e1a3..c56991d 100644 --- a/src/main/java/org/codelibs/core/misc/ValueHolder.java +++ b/src/main/java/org/codelibs/core/misc/ValueHolder.java @@ -64,7 +64,7 @@ public void setValue(final T value) { @Override public String toString() { - return value.toString(); + return String.valueOf(value); } } diff --git a/src/main/java/org/codelibs/core/net/MimeTypeUtil.java b/src/main/java/org/codelibs/core/net/MimeTypeUtil.java index 500d926..73107b1 100644 --- a/src/main/java/org/codelibs/core/net/MimeTypeUtil.java +++ b/src/main/java/org/codelibs/core/net/MimeTypeUtil.java @@ -17,6 +17,7 @@ import static org.codelibs.core.misc.AssertionUtil.assertArgumentNotEmpty; +import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLConnection; @@ -48,7 +49,9 @@ protected MimeTypeUtil() { public static String guessContentType(final String path) { assertArgumentNotEmpty("path", path); - final InputStream is = ResourceUtil.getResourceAsStream(path); + // Wrap in a BufferedInputStream so that guessContentTypeFromStream can always + // mark/reset the stream, regardless of the underlying stream implementation. + final InputStream is = new BufferedInputStream(ResourceUtil.getResourceAsStream(path)); try { final String mimetype = URLConnection.guessContentTypeFromStream(is); if (mimetype != null) { diff --git a/src/main/java/org/codelibs/core/net/URLUtil.java b/src/main/java/org/codelibs/core/net/URLUtil.java index 80d4524..ec98e5a 100644 --- a/src/main/java/org/codelibs/core/net/URLUtil.java +++ b/src/main/java/org/codelibs/core/net/URLUtil.java @@ -198,7 +198,9 @@ public static File toFile(final URL fileUrl) { assertArgumentNotNull("fileUrl", fileUrl); try { - final String path = URLDecoder.decode(fileUrl.getPath(), "UTF-8"); + // A '+' in a URL path is a literal '+', but URLDecoder would decode it to a + // space. Pre-encode it as %2B so that a literal '+' in the path is preserved. + final String path = URLDecoder.decode(fileUrl.getPath().replace("+", "%2B"), "UTF-8"); return new File(path).getAbsoluteFile(); } catch (final Exception e) { throw new ClRuntimeException("ECL0091", asArray(fileUrl), e); diff --git a/src/main/java/org/codelibs/core/nio/ChannelUtil.java b/src/main/java/org/codelibs/core/nio/ChannelUtil.java index ca5f0b6..e182f32 100644 --- a/src/main/java/org/codelibs/core/nio/ChannelUtil.java +++ b/src/main/java/org/codelibs/core/nio/ChannelUtil.java @@ -173,7 +173,18 @@ public static long transfer(final FileChannel from, final FileChannel to) { assertArgumentNotNull("to", to); try { - return from.transferTo(0, from.size(), to); + // FileChannel.transferTo may transfer fewer bytes than requested, + // so loop until the whole source has been transferred. + final long size = from.size(); + long position = 0; + while (position < size) { + final long transferred = from.transferTo(position, size - position, to); + if (transferred <= 0) { + break; + } + position += transferred; + } + return position; } catch (final IOException e) { throw new IORuntimeException(e); } diff --git a/src/main/java/org/codelibs/core/security/MessageDigestUtil.java b/src/main/java/org/codelibs/core/security/MessageDigestUtil.java index a3aee79..d9f410f 100644 --- a/src/main/java/org/codelibs/core/security/MessageDigestUtil.java +++ b/src/main/java/org/codelibs/core/security/MessageDigestUtil.java @@ -17,11 +17,10 @@ import static org.codelibs.core.misc.AssertionUtil.assertArgumentNotEmpty; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import org.codelibs.core.exception.ClIllegalStateException; import org.codelibs.core.exception.NoSuchAlgorithmRuntimeException; /** @@ -75,11 +74,7 @@ public static String digest(final String algorithm, final String text) { } final MessageDigest msgDigest = getInstance(algorithm); - try { - msgDigest.update(text.getBytes("UTF-8")); - } catch (final UnsupportedEncodingException e) { - throw new ClIllegalStateException(e); - } + msgDigest.update(text.getBytes(StandardCharsets.UTF_8)); final byte[] digest = msgDigest.digest(); final StringBuilder buffer = new StringBuilder(200); diff --git a/src/main/java/org/codelibs/core/text/DecimalFormatSymbolsUtil.java b/src/main/java/org/codelibs/core/text/DecimalFormatSymbolsUtil.java index 28ae695..f00051a 100644 --- a/src/main/java/org/codelibs/core/text/DecimalFormatSymbolsUtil.java +++ b/src/main/java/org/codelibs/core/text/DecimalFormatSymbolsUtil.java @@ -63,7 +63,8 @@ public static DecimalFormatSymbols getDecimalFormatSymbols(final Locale locale) symbols = new DecimalFormatSymbols(locale); CACHE.put(locale, symbols); } - return symbols; + // Return a defensive copy so that callers cannot mutate the shared cached instance. + return (DecimalFormatSymbols) symbols.clone(); } } diff --git a/src/main/java/org/codelibs/core/text/JsonUtil.java b/src/main/java/org/codelibs/core/text/JsonUtil.java index 3664b15..7fb8994 100644 --- a/src/main/java/org/codelibs/core/text/JsonUtil.java +++ b/src/main/java/org/codelibs/core/text/JsonUtil.java @@ -24,7 +24,7 @@ public class JsonUtil { /** - * Defualt constructor. + * Default constructor. */ protected JsonUtil() { } diff --git a/src/main/java/org/codelibs/core/text/Tokenizer.java b/src/main/java/org/codelibs/core/text/Tokenizer.java index 70920f3..cae3c78 100644 --- a/src/main/java/org/codelibs/core/text/Tokenizer.java +++ b/src/main/java/org/codelibs/core/text/Tokenizer.java @@ -237,6 +237,9 @@ public int nextToken() { * @return The string that has already been read. */ public String getReadString() { + if (colno == 0) { + return ""; + } return str.substring(0, colno - 1); } diff --git a/src/main/java/org/codelibs/core/timer/TimeoutManager.java b/src/main/java/org/codelibs/core/timer/TimeoutManager.java index e2893e2..4aea8ca 100644 --- a/src/main/java/org/codelibs/core/timer/TimeoutManager.java +++ b/src/main/java/org/codelibs/core/timer/TimeoutManager.java @@ -177,7 +177,13 @@ public void run() { if (logger.isDebugEnabled()) { logger.debug("TimeoutManagerThread stopped."); } - thread = null; + synchronized (this) { + // Only clear the reference if it still points to this thread; a concurrent + // stop()/start() may have already replaced it with a new worker thread. + if (thread == Thread.currentThread()) { + thread = null; + } + } try { executorService.shutdown(); executorService.awaitTermination(60, TimeUnit.SECONDS); diff --git a/src/main/java/org/codelibs/core/timer/TimeoutTask.java b/src/main/java/org/codelibs/core/timer/TimeoutTask.java index 118cf40..4756d5d 100644 --- a/src/main/java/org/codelibs/core/timer/TimeoutTask.java +++ b/src/main/java/org/codelibs/core/timer/TimeoutTask.java @@ -37,9 +37,9 @@ public class TimeoutTask { private final boolean permanent; - private long startTime; + private volatile long startTime; - private int status = ACTIVE; + private volatile int status = ACTIVE; TimeoutTask(final TimeoutTarget timeoutTarget, final int timeout, final boolean permanent) { this.timeoutTarget = timeoutTarget; diff --git a/src/main/java/org/codelibs/core/xml/SchemaFactoryUtil.java b/src/main/java/org/codelibs/core/xml/SchemaFactoryUtil.java index 8134639..f1363f4 100644 --- a/src/main/java/org/codelibs/core/xml/SchemaFactoryUtil.java +++ b/src/main/java/org/codelibs/core/xml/SchemaFactoryUtil.java @@ -92,5 +92,12 @@ private static void disableExternalResources(final SchemaFactory schemaFactory) logger.debug("Failed to set a property.", e); } } + try { + schemaFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + } catch (final Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to set a feature.", e); + } + } } } diff --git a/src/main/java/org/codelibs/core/zip/ZipFileUtil.java b/src/main/java/org/codelibs/core/zip/ZipFileUtil.java index 81592d6..397cd35 100644 --- a/src/main/java/org/codelibs/core/zip/ZipFileUtil.java +++ b/src/main/java/org/codelibs/core/zip/ZipFileUtil.java @@ -126,7 +126,8 @@ public static String toZipFilePath(final URL zipUrl) { final String urlString = zipUrl.getPath(); final int pos = urlString.lastIndexOf('!'); final String zipFilePath = urlString.substring(0, pos); - final File zipFile = new File(URLUtil.decode(zipFilePath, "UTF8")); + // Preserve a literal '+' in the path (URLUtil.decode would turn it into a space). + final File zipFile = new File(URLUtil.decode(zipFilePath.replace("+", "%2B"), "UTF8")); return FileUtil.getCanonicalPath(zipFile); } diff --git a/src/test/java/org/codelibs/core/beans/impl/BeanDescImplTest.java b/src/test/java/org/codelibs/core/beans/impl/BeanDescImplTest.java index 02c868b..d4ebbbc 100644 --- a/src/test/java/org/codelibs/core/beans/impl/BeanDescImplTest.java +++ b/src/test/java/org/codelibs/core/beans/impl/BeanDescImplTest.java @@ -21,6 +21,7 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertThrows; import java.math.BigDecimal; import java.util.Date; @@ -144,6 +145,20 @@ public void testGetMethodNoException() throws Exception { assertThat(methodDesc, is(nullValue())); } + /** + * Regression: when number adjustment fails for a candidate method, the failure must be + * reported as {@link MethodNotFoundRuntimeException} (not the underlying conversion + * exception) and the caller's argument array must be left unchanged. + */ + @Test + public void testGetSuitableMethodDescDoesNotMutateArgsOnFailure() { + final BeanDesc beanDesc = new BeanDescImpl(MyBean.class); + final Object[] args = { "1", "notanumber" }; + assertThrows(MethodNotFoundRuntimeException.class, () -> beanDesc.getSuitableMethodDesc("add2", args)); + assertThat(args[0], is((Object) "1")); + assertThat(args[1], is((Object) "notanumber")); + } + /** * @throws Exception */ diff --git a/src/test/java/org/codelibs/core/collection/ArrayMapTest.java b/src/test/java/org/codelibs/core/collection/ArrayMapTest.java index 0f9305d..d60df01 100644 --- a/src/test/java/org/codelibs/core/collection/ArrayMapTest.java +++ b/src/test/java/org/codelibs/core/collection/ArrayMapTest.java @@ -224,6 +224,39 @@ public void testEqaulas() throws Exception { assertThat(map.equals(copy), is(not(true))); } + /** + * Verifies that {@link ArrayMap#clone()} produces an independent copy whose hash + * buckets resolve correctly and whose entries are not shared with the original. + * + * @throws Exception + */ + @Test + public void testClone() throws Exception { + @SuppressWarnings("unchecked") + final ArrayMap copy = (ArrayMap) map.clone(); + assertThat(copy.size(), is(3)); + // Keys must resolve through the rebuilt bucket table, not a truncated one. + assertThat(copy.get(null), is(nullValue())); + assertThat(copy.get("1"), is("test")); + assertThat(copy.get("2"), is("test2")); + // Insertion order must be preserved. + assertThat(copy.getAt(0), is(nullValue())); + assertThat(copy.getAt(1), is("test")); + assertThat(copy.getAt(2), is("test2")); + // put on the clone must not throw and must not modify the original. + copy.put("3", "test3"); + copy.put("4", "test4"); + assertThat(copy.get("3"), is("test3")); + assertThat(copy.get("4"), is("test4")); + assertThat(map.containsKey("3"), is(not(true))); + assertThat(map.size(), is(3)); + // remove on the clone must not corrupt the original's entries. + assertThat(copy.remove("1"), is("test")); + assertThat(copy.containsKey("1"), is(not(true))); + assertThat(map.get("1"), is("test")); + assertThat(map.containsKey("1"), is(true)); + } + /** * @throws Exception */ diff --git a/src/test/java/org/codelibs/core/collection/CaseInsensitiveMapTest.java b/src/test/java/org/codelibs/core/collection/CaseInsensitiveMapTest.java index 76f31d2..359fe0e 100644 --- a/src/test/java/org/codelibs/core/collection/CaseInsensitiveMapTest.java +++ b/src/test/java/org/codelibs/core/collection/CaseInsensitiveMapTest.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertThat; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import org.junit.After; @@ -105,6 +106,40 @@ public void testPutAll() throws Exception { assertThat(map.size(), is(4)); } + /** + * A {@literal null} key must be supported the same way the parent {@link ArrayMap} supports it. + * + * @throws Exception + */ + @Test + public void testNullKey() throws Exception { + assertThat(map.put(null, "nullValue"), is(nullValue())); + assertThat(map.containsKey(null), is(true)); + assertThat(map.get(null), is("nullValue")); + assertThat(map.remove(null), is("nullValue")); + assertThat(map.containsKey(null), is(not(true))); + } + + /** + * Key folding must be locale-independent (e.g. the Turkish dotless-i must not break + * case-insensitive lookups of ASCII keys). + * + * @throws Exception + */ + @Test + public void testLocaleIndependentKey() throws Exception { + final Locale defaultLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.forLanguageTag("tr")); + final CaseInsensitiveMap m = new CaseInsensitiveMap(); + m.put("ID", "value"); + assertThat(m.get("id"), is("value")); + assertThat(m.containsKey("id"), is(true)); + } finally { + Locale.setDefault(defaultLocale); + } + } + /** * @throws Exception */ diff --git a/src/test/java/org/codelibs/core/collection/CaseInsensitiveSetTest.java b/src/test/java/org/codelibs/core/collection/CaseInsensitiveSetTest.java index 66b673a..46064b7 100644 --- a/src/test/java/org/codelibs/core/collection/CaseInsensitiveSetTest.java +++ b/src/test/java/org/codelibs/core/collection/CaseInsensitiveSetTest.java @@ -16,10 +16,12 @@ package org.codelibs.core.collection; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import java.util.Set; +import org.codelibs.core.io.SerializeUtil; import org.junit.Test; /** @@ -37,4 +39,21 @@ public void testContains() throws Exception { assertThat(set.contains("ONE"), is(true)); } + /** + * The set must survive serialization even though the backing map is {@code transient}. + * + * @throws Exception + */ + @Test + public void testSerialize() throws Exception { + final CaseInsensitiveSet set = new CaseInsensitiveSet(); + set.add("one"); + set.add("two"); + final CaseInsensitiveSet copy = (CaseInsensitiveSet) SerializeUtil.serialize(set); + assertThat(copy.size(), is(2)); + assertThat(copy.contains("ONE"), is(true)); + assertThat(copy.contains("Two"), is(true)); + assertThat(copy.contains("three"), is(not(true))); + } + } diff --git a/src/test/java/org/codelibs/core/collection/LruHashSetTest.java b/src/test/java/org/codelibs/core/collection/LruHashSetTest.java new file mode 100644 index 0000000..b990754 --- /dev/null +++ b/src/test/java/org/codelibs/core/collection/LruHashSetTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.collection; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; + +import org.codelibs.core.io.SerializeUtil; +import org.junit.Test; + +/** + * @author shinsuke + */ +public class LruHashSetTest { + + /** + * @throws Exception + */ + @Test + public void testLimit() throws Exception { + final LruHashSet set = new LruHashSet<>(2); + set.add("aaa"); + set.add("bbb"); + set.add("ccc"); + assertThat(set.size(), is(2)); + assertThat(set.contains("aaa"), is(not(true))); + assertThat(set.contains("bbb"), is(true)); + assertThat(set.contains("ccc"), is(true)); + } + + /** + * The set stores a non-serializable sentinel as the backing map value, so it must + * serialize the elements (and the limit size) itself rather than the map values. + * + * @throws Exception + */ + @Test + public void testSerialize() throws Exception { + final LruHashSet set = new LruHashSet<>(3); + set.add("aaa"); + set.add("bbb"); + @SuppressWarnings("unchecked") + final LruHashSet copy = (LruHashSet) SerializeUtil.serialize(set); + assertThat(copy.size(), is(2)); + assertThat(copy.contains("aaa"), is(true)); + assertThat(copy.contains("bbb"), is(true)); + assertThat(copy.contains("ccc"), is(not(true))); + // The limit size must survive serialization. + copy.add("ccc"); + copy.add("ddd"); + assertThat(copy.size(), is(3)); + } + +} diff --git a/src/test/java/org/codelibs/core/convert/BinaryConversionUtilTest.java b/src/test/java/org/codelibs/core/convert/BinaryConversionUtilTest.java index c0be871..92ecb63 100644 --- a/src/test/java/org/codelibs/core/convert/BinaryConversionUtilTest.java +++ b/src/test/java/org/codelibs/core/convert/BinaryConversionUtilTest.java @@ -19,6 +19,8 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; +import java.nio.charset.StandardCharsets; + import org.codelibs.core.exception.ClIllegalArgumentException; import org.junit.Rule; import org.junit.Test; @@ -49,6 +51,16 @@ public void testToBinary() { assertThat(BinaryConversionUtil.toBinary("hoge"), is("hoge".getBytes())); } + /** + * A {@link String} must be encoded with a fixed charset (UTF-8) so the result does not + * depend on the platform default charset. + */ + @Test + public void testToBinaryUtf8() { + final String value = "あいう"; // Japanese hiragana + assertThat(BinaryConversionUtil.toBinary(value), is(value.getBytes(StandardCharsets.UTF_8))); + } + /** * Test method for * {@link org.codelibs.core.convert.BinaryConversionUtil#toBinary(java.lang.Object)} diff --git a/src/test/java/org/codelibs/core/convert/TimestampConversionUtilTest.java b/src/test/java/org/codelibs/core/convert/TimestampConversionUtilTest.java index a47d590..7e864b4 100644 --- a/src/test/java/org/codelibs/core/convert/TimestampConversionUtilTest.java +++ b/src/test/java/org/codelibs/core/convert/TimestampConversionUtilTest.java @@ -15,6 +15,7 @@ */ package org.codelibs.core.convert; +import static org.codelibs.core.convert.TimestampConversionUtil.getLongPattern; import static org.codelibs.core.convert.TimestampConversionUtil.toCalendar; import static org.codelibs.core.convert.TimestampConversionUtil.toDate; import static org.codelibs.core.convert.TimestampConversionUtil.toPlainPattern; @@ -30,6 +31,7 @@ import java.util.Locale; import java.util.TimeZone; +import org.codelibs.core.exception.NullArgumentException; import org.codelibs.core.misc.LocaleUtil; import org.junit.After; import org.junit.Before; @@ -234,6 +236,19 @@ public void testToCalendar_SpecificPattern() throws Exception { assertThat(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(calendar.getTime()), is("2010/09/07 11:49:10")); } + /** + * The locale passed to {@code toCalendar} must be honored when parsing the pattern. + * The default locale is {@link Locale#JAPANESE} (see {@link #setUp()}), so the English + * month name only parses when the explicitly supplied {@link Locale#US} is used. + * + * @throws Exception + */ + @Test + public void testToCalendar_SpecificPatternWithLocale() throws Exception { + final Calendar calendar = toCalendar("Sep 7, 2010 11:49:10", "MMM d, yyyy HH:mm:ss", Locale.US); + assertThat(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(calendar.getTime()), is("2010/09/07 11:49:10")); + } + /** * @throws Exception */ @@ -334,4 +349,15 @@ public void testToPlainPattern() throws Exception { assertThat(toPlainPattern("y/M/d H:m:s"), is("yyMMdd HHmmss")); } + /** + * {@code getLongPattern} must reject a {@code null} locale, consistent with the other + * {@code getXxxPattern(Locale)} methods. + * + * @throws Exception + */ + @Test(expected = NullArgumentException.class) + public void testGetLongPattern_NullLocale() throws Exception { + getLongPattern(null); + } + } diff --git a/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java b/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java index e17c189..4446747 100644 --- a/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java +++ b/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java @@ -20,6 +20,10 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertThat; +import java.security.Key; + +import javax.crypto.spec.SecretKeySpec; + import org.junit.Test; /** @@ -158,4 +162,40 @@ public void testUnicodeText() { assertThat(decrypted, is(original)); } + + @Test + public void testKeyBasedCipherReinitializedPerKey() { + // Regression: a pooled cipher must be re-initialized with the given key on every + // operation. Before the fix, encrypt(data, keyB) reused the cipher still initialized + // with keyA, so keyB was silently ignored (encA == encB) and decrypt(encB, keyB) failed. + final CachedCipher cipher = new CachedCipher(); + final Key keyA = new SecretKeySpec("0123456789abcdef".getBytes(), "Blowfish"); + final Key keyB = new SecretKeySpec("fedcba9876543210".getBytes(), "Blowfish"); + + final byte[] data = "Hello World".getBytes(); + + final byte[] encA = cipher.encrypt(data, keyA); + final byte[] encB = cipher.encrypt(data, keyB); + + assertThat(encA, is(not(encB))); + assertArrayEquals(data, cipher.decrypt(encA, keyA)); + assertArrayEquals(data, cipher.decrypt(encB, keyB)); + } + + @Test + public void testStringKeyChangeInvalidatesPooledCipher() { + // Regression: changing the key on a reused instance must take effect. Before the fix, + // the pooled cipher retained the previous key and encrypted with it. + final CachedCipher cipher = new CachedCipher(); + + cipher.setKey("keyOne"); + final byte[] data = "Hello World".getBytes(); + final byte[] encOne = cipher.encrypt(data); + + cipher.setKey("keyTwo"); + final byte[] encTwo = cipher.encrypt(data); + + assertThat(encOne, is(not(encTwo))); + assertArrayEquals(data, cipher.decrypt(encTwo)); + } } diff --git a/src/test/java/org/codelibs/core/io/CopyUtilTest.java b/src/test/java/org/codelibs/core/io/CopyUtilTest.java index 38ed874..ce42870 100644 --- a/src/test/java/org/codelibs/core/io/CopyUtilTest.java +++ b/src/test/java/org/codelibs/core/io/CopyUtilTest.java @@ -22,6 +22,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileOutputStream; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; @@ -164,4 +165,32 @@ public void testUrlToFile() throws Exception { assertThat(writer.toString(), is(urlString)); } + /** + * Copying a multi-megabyte file must transfer every byte, even when the + * underlying channel transfer completes in more than one step. + * + * @throws Exception + */ + @Test + public void testFileToFile_LargeContentIsComplete() throws Exception { + final File src = File.createTempFile("copyutil-src", ".dat"); + final File dest = File.createTempFile("copyutil-dest", ".dat"); + try { + final byte[] expected = new byte[3 * 1024 * 1024 + 123]; // ~3MB, not buffer-aligned + for (int i = 0; i < expected.length; i++) { + expected[i] = (byte) (i * 31 + 7); + } + try (FileOutputStream fos = new FileOutputStream(src)) { + fos.write(expected); + } + + final int result = copy(src, dest); + assertThat(result, is(expected.length)); + assertThat(FileUtil.readBytes(dest, expected.length), is(expected)); + } finally { + src.delete(); + dest.delete(); + } + } + } diff --git a/src/test/java/org/codelibs/core/io/FileUtilTest.java b/src/test/java/org/codelibs/core/io/FileUtilTest.java index 6678091..4d2b1f1 100644 --- a/src/test/java/org/codelibs/core/io/FileUtilTest.java +++ b/src/test/java/org/codelibs/core/io/FileUtilTest.java @@ -339,6 +339,28 @@ public void testReadBytes_CustomMaxSize_VeryLarge() throws Exception { assertThat(new String(bytes, "UTF-8"), is(content)); } + /** + * Test readBytes returns the complete content for a multi-megabyte file, so + * that a partial channel read cannot leave the trailing bytes zero-filled. + * + * @throws Exception + */ + @Test + public void testReadBytes_LargeContentIsComplete() throws Exception { + final File file = tempFolder.newFile("large_complete.dat"); + final byte[] expected = new byte[3 * 1024 * 1024 + 123]; // ~3MB, not buffer-aligned + for (int i = 0; i < expected.length; i++) { + expected[i] = (byte) (i * 31 + 7); + } + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(expected); + } + + final byte[] actual = FileUtil.readBytes(file, expected.length); + assertThat(actual.length, is(expected.length)); + assertThat(actual, is(expected)); + } + private String getPath(final String fileName) { return getClass().getName().replace('.', '/').replaceFirst(getClass().getSimpleName(), fileName); } diff --git a/src/test/java/org/codelibs/core/io/SerializeUtilTest.java b/src/test/java/org/codelibs/core/io/SerializeUtilTest.java index d9fc5d4..b7a0f02 100644 --- a/src/test/java/org/codelibs/core/io/SerializeUtilTest.java +++ b/src/test/java/org/codelibs/core/io/SerializeUtilTest.java @@ -206,6 +206,31 @@ public void testFromBinaryToObject_CollectionWithNulls() throws Exception { assertEquals("third", result.get(2)); } + /** + * Test that the default filter rejects a payload whose object-graph depth + * exceeds the resource limit, even though every class is on the allowlist. + * + * @throws Exception + */ + public void testFromBinaryToObject_DefaultFilter_RejectsDeepGraph() throws Exception { + final ArrayList root = new ArrayList<>(); + ArrayList current = root; + // Nest well beyond MAX_DEPTH (100) but not deep enough to risk a + // StackOverflowError during serialization. + for (int i = 0; i < 150; i++) { + final ArrayList child = new ArrayList<>(); + current.add(child); + current = child; + } + final byte[] binary = SerializeUtil.fromObjectToBinary(root); + try { + SerializeUtil.fromBinaryToObject(binary); + fail("Expected IORuntimeException for a deeply nested object graph"); + } catch (final IORuntimeException e) { + // Expected: rejected by the resource limit in the default filter. + } + } + /** * Test helper class for serialization tests */ diff --git a/src/test/java/org/codelibs/core/lang/ClassUtilTest.java b/src/test/java/org/codelibs/core/lang/ClassUtilTest.java index aaf8107..44f0cb3 100644 --- a/src/test/java/org/codelibs/core/lang/ClassUtilTest.java +++ b/src/test/java/org/codelibs/core/lang/ClassUtilTest.java @@ -22,6 +22,8 @@ import static org.junit.Assert.assertThat; import org.codelibs.core.exception.EmptyArgumentException; +import org.codelibs.core.exception.InstantiationRuntimeException; +import org.codelibs.core.exception.InvocationTargetRuntimeException; import org.codelibs.core.exception.NoSuchConstructorRuntimeException; import org.codelibs.core.exception.NoSuchFieldRuntimeException; import org.junit.Test; @@ -198,4 +200,40 @@ public void testConvertClass() { assertThat(ClassUtil.convertClass("java.lang.String"), is(sameClass(String.class))); } + /** + * A class with an accessible no-arg constructor is instantiated. + */ + @Test + public void testNewInstance() { + assertThat(ClassUtil.newInstance(StringBuilder.class), is(not(nullValue()))); + } + + /** + * An abstract class is still reported as {@link InstantiationRuntimeException}. + */ + @Test(expected = InstantiationRuntimeException.class) + public void testNewInstance_abstract() { + ClassUtil.newInstance(AbstractHoge.class); + } + + /** + * An exception raised by the constructor is wrapped in {@link InvocationTargetRuntimeException}. + */ + @Test(expected = InvocationTargetRuntimeException.class) + public void testNewInstance_throwingConstructor() { + ClassUtil.newInstance(ThrowingHoge.class); + } + + /** Abstract class used by {@link #testNewInstance_abstract()}. */ + public abstract static class AbstractHoge { + } + + /** Class whose constructor always throws, used by {@link #testNewInstance_throwingConstructor()}. */ + public static class ThrowingHoge { + /** Always throws to exercise the constructor failure path. */ + public ThrowingHoge() { + throw new IllegalStateException("boom"); + } + } + } diff --git a/src/test/java/org/codelibs/core/lang/StringUtilTest.java b/src/test/java/org/codelibs/core/lang/StringUtilTest.java index 441618c..8629c76 100644 --- a/src/test/java/org/codelibs/core/lang/StringUtilTest.java +++ b/src/test/java/org/codelibs/core/lang/StringUtilTest.java @@ -46,6 +46,18 @@ public void testReplace() throws Exception { assertEquals("6", "a\\nb", StringUtil.replace("a\nb", "\n", "\\n")); } + /** + * An empty {@code fromText} must return the text unchanged instead of looping forever. + * + * @throws Exception + */ + @Test(timeout = 5000) + public void testReplace_emptyFromText() throws Exception { + assertEquals("abc", StringUtil.replace("abc", "", "x")); + assertEquals("", StringUtil.replace("", "", "x")); + assertNull(StringUtil.replace(null, "", "x")); + } + /** * @throws Exception */ diff --git a/src/test/java/org/codelibs/core/misc/DynamicPropertiesTest.java b/src/test/java/org/codelibs/core/misc/DynamicPropertiesTest.java new file mode 100644 index 0000000..48fb7b8 --- /dev/null +++ b/src/test/java/org/codelibs/core/misc/DynamicPropertiesTest.java @@ -0,0 +1,171 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.misc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.nio.file.Files; +import java.util.HashMap; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Tests for {@link DynamicProperties}. + */ +public class DynamicPropertiesTest { + + private File tempDir; + + /** + * @throws Exception + */ + @Before + public void setUp() throws Exception { + tempDir = Files.createTempDirectory("dynprops").toFile(); + } + + /** + * @throws Exception + */ + @After + public void tearDown() throws Exception { + deleteRecursively(tempDir); + } + + private static void deleteRecursively(final File file) { + if (file == null || !file.exists()) { + return; + } + final File[] children = file.listFiles(); + if (children != null) { + for (final File child : children) { + deleteRecursively(child); + } + } + file.delete(); + } + + private DynamicProperties newProps() { + return new DynamicProperties(new File(tempDir, "test.properties")); + } + + /** + * Repeated calls faster than the check interval must not slide the throttle window and + * suppress the modification check forever. + * + * @throws Exception + */ + @Test + public void testIsUpdated_throttleWindowDoesNotSlide() throws Exception { + final DynamicProperties props = newProps(); + props.checkInterval = 2000L; + // Force the real check to report "updated" whenever it actually runs. + props.lastModified = 0L; + // Place the last check just inside the throttle window. + props.lastChecked = System.currentTimeMillis() - 1800L; + + // Inside the throttle window: returns false without advancing lastChecked. + assertFalse(props.isUpdated()); + + // Once the interval elapses the real check must run, even though calls kept coming. + Thread.sleep(400L); + assertTrue(props.isUpdated()); + } + + /** + * {@link DynamicProperties#forEach} must operate on the backing properties, not the empty super class. + * + * @throws Exception + */ + @Test + public void testForEachDelegatesToInternalProperties() throws Exception { + final DynamicProperties props = newProps(); + props.setProperty("a", "1"); + props.setProperty("b", "2"); + + final Map collected = new HashMap<>(); + props.forEach(collected::put); + + assertEquals(2, collected.size()); + assertEquals("1", collected.get("a")); + assertEquals("2", collected.get("b")); + } + + /** + * {@link DynamicProperties#getOrDefault} must read from the backing properties. + * + * @throws Exception + */ + @Test + public void testGetOrDefaultDelegatesToInternalProperties() throws Exception { + final DynamicProperties props = newProps(); + props.setProperty("a", "1"); + + assertEquals("1", props.getOrDefault("a", "z")); + assertEquals("z", props.getOrDefault("missing", "z")); + } + + /** + * {@link DynamicProperties#computeIfAbsent} must write to the backing properties so that + * {@link DynamicProperties#getProperty} can read the value back. + * + * @throws Exception + */ + @Test + public void testComputeIfAbsentDelegatesToInternalProperties() throws Exception { + final DynamicProperties props = newProps(); + + props.computeIfAbsent("k", k -> "v"); + + assertEquals("v", props.getProperty("k")); + } + + /** + * A path whose intermediate directories do not exist must be created. + * + * @throws Exception + */ + @Test + public void testConstructorCreatesMissingNestedDirectories() throws Exception { + final File nested = new File(tempDir, "a/b/c/test.properties"); + + new DynamicProperties(nested); + + assertTrue(nested.exists()); + } + + /** + * A bare file name (no parent directory component) must not raise a {@link NullPointerException}. + * + * @throws Exception + */ + @Test + public void testConstructorWithBareFilenameDoesNotThrowNpe() throws Exception { + final File bare = new File("dynprops_" + System.nanoTime() + ".properties"); + try { + new DynamicProperties(bare); + assertTrue(bare.exists()); + } finally { + bare.delete(); + } + } +} diff --git a/src/test/java/org/codelibs/core/misc/ValueHolderTest.java b/src/test/java/org/codelibs/core/misc/ValueHolderTest.java new file mode 100644 index 0000000..2eadba3 --- /dev/null +++ b/src/test/java/org/codelibs/core/misc/ValueHolderTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.misc; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * Tests for {@link ValueHolder}. + */ +public class ValueHolderTest { + + /** + * A null value must not raise a {@link NullPointerException} from {@link ValueHolder#toString()}. + * + * @throws Exception + */ + @Test + public void testToString_nullValue() throws Exception { + assertEquals("null", new ValueHolder().toString()); + } + + /** + * @throws Exception + */ + @Test + public void testToString_nonNullValue() throws Exception { + assertEquals("abc", new ValueHolder<>("abc").toString()); + } +} diff --git a/src/test/java/org/codelibs/core/net/URLUtilTest.java b/src/test/java/org/codelibs/core/net/URLUtilTest.java index 18b2d1b..3eee194 100644 --- a/src/test/java/org/codelibs/core/net/URLUtilTest.java +++ b/src/test/java/org/codelibs/core/net/URLUtilTest.java @@ -60,4 +60,16 @@ public void testToFile() throws Exception { assertEquals(file.getAbsoluteFile(), URLUtil.toFile(new URL("file:Program%20Files/hoge.txt"))); } + /** + * A literal '+' in a file path must be preserved (not decoded to a space). + * + * @throws Exception + */ + public void testToFileWithPlus() throws Exception { + final File file = new File("my+project/hoge.txt"); + assertEquals(file.getAbsoluteFile(), URLUtil.toFile(new URL("file:my+project/hoge.txt"))); + // Encoded space (%20) must still decode to a space. + assertEquals(new File("my project/hoge.txt").getAbsoluteFile(), URLUtil.toFile(new URL("file:my%20project/hoge.txt"))); + } + } diff --git a/src/test/java/org/codelibs/core/text/DecimalFormatSymbolsUtilTest.java b/src/test/java/org/codelibs/core/text/DecimalFormatSymbolsUtilTest.java index cccc9e9..66c1472 100644 --- a/src/test/java/org/codelibs/core/text/DecimalFormatSymbolsUtilTest.java +++ b/src/test/java/org/codelibs/core/text/DecimalFormatSymbolsUtilTest.java @@ -34,4 +34,19 @@ public void testGetDecimalFormatSymbols() throws Exception { System.out.println("DecimalSeparator:" + symbols.getDecimalSeparator()); System.out.println("GroupingSeparator:" + symbols.getGroupingSeparator()); } + + /** + * The returned {@link DecimalFormatSymbols} must be a defensive copy so that mutating it + * does not corrupt the shared cached instance. + * + * @throws Exception + */ + public void testGetDecimalFormatSymbolsReturnsDefensiveCopy() throws Exception { + final DecimalFormatSymbols first = DecimalFormatSymbolsUtil.getDecimalFormatSymbols(Locale.US); + final char originalDecimalSeparator = first.getDecimalSeparator(); + first.setDecimalSeparator('#'); + final DecimalFormatSymbols second = DecimalFormatSymbolsUtil.getDecimalFormatSymbols(Locale.US); + assertFalse(first == second); + assertEquals(originalDecimalSeparator, second.getDecimalSeparator()); + } } diff --git a/src/test/java/org/codelibs/core/text/TokenizerTest.java b/src/test/java/org/codelibs/core/text/TokenizerTest.java index bbedff0..84c5373 100644 --- a/src/test/java/org/codelibs/core/text/TokenizerTest.java +++ b/src/test/java/org/codelibs/core/text/TokenizerTest.java @@ -36,6 +36,17 @@ public void testEOF() throws Exception { assertThat(tokenizer.nextToken(), is(Tokenizer.TT_EOF)); } + /** + * {@code getReadString} must not throw when called before any token has been read. + * + * @throws Exception + */ + @Test + public void testGetReadStringBeforeNextToken() throws Exception { + final Tokenizer tokenizer = new Tokenizer("abc"); + assertThat(tokenizer.getReadString(), is("")); + } + /** * @throws Exception */ From 6c04ee2251e3de62d1cbd9c37dcb07a2b1440fa3 Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sat, 4 Jul 2026 08:07:19 +0900 Subject: [PATCH 2/2] feat(core): add java.time conversions, record support, and opt-in secure APIs Additive enhancements that do not change any existing behavior or defaults. - convert: new TemporalConversionUtil converts Date/Calendar/epoch-millis/ISO strings and java.time values to LocalDate/LocalDateTime/LocalTime/Instant/ OffsetDateTime/ZonedDateTime (system-default zone, or an explicit ZoneId) - beans: BeanDescImpl detects record components as read-only properties and instantiates records through their canonical constructor - crypto: CachedCipher.encryptWithIv/decryptWithIv provide AES/GCM authenticated encryption with a fresh random IV per call; the default Blowfish/ECB pool is left unchanged - io: CloseableUtil.closeAndRethrow propagates close failures (for output streams); FileUtil.isRealPathSafe resolves symbolic links via toRealPath - exception: add InvalidAlgorithmParameterRuntimeException (message ECL0117) Adds regression tests for all new APIs. --- .../core/beans/impl/BeanDescImpl.java | 21 + .../core/convert/TemporalConversionUtil.java | 354 +++++++++++++ .../codelibs/core/crypto/CachedCipher.java | 104 ++++ ...lidAlgorithmParameterRuntimeException.java | 41 ++ .../org/codelibs/core/io/CloseableUtil.java | 25 + .../java/org/codelibs/core/io/FileUtil.java | 33 ++ src/main/resources/CLMessages.properties | 1 + .../core/beans/impl/RecordBeanDescTest.java | 131 +++++ .../convert/TemporalConversionUtilTest.java | 496 ++++++++++++++++++ .../core/crypto/CachedCipherTest.java | 26 + .../codelibs/core/io/CloseableUtilTest.java | 27 + .../org/codelibs/core/io/FileUtilTest.java | 39 ++ 12 files changed, 1298 insertions(+) create mode 100644 src/main/java/org/codelibs/core/convert/TemporalConversionUtil.java create mode 100644 src/main/java/org/codelibs/core/exception/InvalidAlgorithmParameterRuntimeException.java create mode 100644 src/test/java/org/codelibs/core/beans/impl/RecordBeanDescTest.java create mode 100644 src/test/java/org/codelibs/core/convert/TemporalConversionUtilTest.java diff --git a/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java b/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java index 8f959fc..68d155c 100644 --- a/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java +++ b/src/main/java/org/codelibs/core/beans/impl/BeanDescImpl.java @@ -29,6 +29,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.lang.reflect.RecordComponent; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Arrays; @@ -494,6 +495,9 @@ protected static boolean adjustNumber(final Class[] paramTypes, final Object[ * Prepares {@link PropertyDesc}. */ protected void setupPropertyDescs() { + if (beanClass.isRecord()) { + setupRecordPropertyDescs(); + } for (final Method m : beanClass.getMethods()) { if (m.isBridge() || m.isSynthetic()) { continue; @@ -526,6 +530,23 @@ protected void setupPropertyDescs() { invalidPropertyNames.clear(); } + /** + * Prepares read-only {@link PropertyDesc}s for the components of a {@link Record}. + *

+ * Each record component is registered as a read-only property whose read method is the component's + * accessor (the prefix-less {@code name()} form). Records are immutable, so no write method is set. + *

+ */ + protected void setupRecordPropertyDescs() { + for (final RecordComponent component : beanClass.getRecordComponents()) { + final Method accessor = component.getAccessor(); + if (accessor == null) { + continue; + } + setupReadMethod(accessor, component.getName()); + } + } + /** * Prepares the getter method. * diff --git a/src/main/java/org/codelibs/core/convert/TemporalConversionUtil.java b/src/main/java/org/codelibs/core/convert/TemporalConversionUtil.java new file mode 100644 index 0000000..736f4fb --- /dev/null +++ b/src/main/java/org/codelibs/core/convert/TemporalConversionUtil.java @@ -0,0 +1,354 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.convert; + +import static org.codelibs.core.lang.StringUtil.isEmpty; +import static org.codelibs.core.misc.AssertionUtil.assertArgumentNotNull; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.Calendar; +import java.util.Date; + +import org.codelibs.core.exception.ParseRuntimeException; + +/** + * Utility for converting objects to {@code java.time} types such as {@link LocalDate}, {@link LocalDateTime}, {@link LocalTime}, + * {@link Instant}, {@link OffsetDateTime}, and {@link ZonedDateTime}. + *

+ * This complements {@link DateConversionUtil}, {@link TimeConversionUtil}, and {@link TimestampConversionUtil}, which convert to the legacy + * {@link Date}, {@link Calendar}, and {@link java.sql.Timestamp} types. + *

+ *

+ * The following source object types are supported: + *

+ *
    + *
  • The target {@code java.time} type itself (returned as-is).
  • + *
  • {@link Instant}, treated as an absolute point on the time line.
  • + *
  • {@link Date} (including {@link java.sql.Timestamp}, {@link java.sql.Date}, and {@link java.sql.Time}), converted from its millisecond + * value. {@link java.sql.Timestamp} additionally preserves nanosecond precision.
  • + *
  • {@link Calendar}, converted from its instant.
  • + *
  • {@link Number} (for example {@link Long}), interpreted as epoch milliseconds.
  • + *
  • {@link String} in ISO-8601 format, parsed with the {@code parse} method of the target type (for example {@link LocalDate#parse}).
  • + *
+ *

+ * A {@literal null} source object is always converted to {@literal null}. Any other unsupported source object is converted from its + * {@link Object#toString()} representation, and a {@link ParseRuntimeException} is thrown when it cannot be parsed. + *

+ *

+ * Converting from an absolute point on the time line (a {@link Date}, {@link Calendar}, {@link Instant}, or epoch milliseconds) to a + * zone-dependent type requires a {@link ZoneId}. The overloads that do not take a {@link ZoneId} use {@link ZoneId#systemDefault()}. The + * zone is not used when the source is a {@link String}, because ISO-8601 strings already carry their own zone or offset information (or none + * at all). + *

+ * + * @author shinsuke + * @see DateConversionUtil + * @see TimeConversionUtil + * @see TimestampConversionUtil + */ +public abstract class TemporalConversionUtil { + + /** + * Do not instantiate. + */ + protected TemporalConversionUtil() { + } + + /** + * Converts the given object to a {@link LocalDate} using the system default time zone. + * + * @param src + * The source object to convert. + * @return The converted {@link LocalDate}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static LocalDate toLocalDate(final Object src) { + return toLocalDate(src, ZoneId.systemDefault()); + } + + /** + * Converts the given object to a {@link LocalDate}. + * + * @param src + * The source object to convert. + * @param zoneId + * The time zone used when the source is an absolute point on the time line. Must not be {@literal null}. + * @return The converted {@link LocalDate}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static LocalDate toLocalDate(final Object src, final ZoneId zoneId) { + assertArgumentNotNull("zoneId", zoneId); + if (src == null) { + return null; + } + if (src instanceof LocalDate) { + return (LocalDate) src; + } + final Instant instant = toEpochInstant(src); + if (instant != null) { + return instant.atZone(zoneId).toLocalDate(); + } + final String str = src.toString(); + if (isEmpty(str)) { + return null; + } + try { + return LocalDate.parse(str); + } catch (final DateTimeParseException e) { + throw new ParseRuntimeException(str); + } + } + + /** + * Converts the given object to a {@link LocalDateTime} using the system default time zone. + * + * @param src + * The source object to convert. + * @return The converted {@link LocalDateTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static LocalDateTime toLocalDateTime(final Object src) { + return toLocalDateTime(src, ZoneId.systemDefault()); + } + + /** + * Converts the given object to a {@link LocalDateTime}. + * + * @param src + * The source object to convert. + * @param zoneId + * The time zone used when the source is an absolute point on the time line. Must not be {@literal null}. + * @return The converted {@link LocalDateTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static LocalDateTime toLocalDateTime(final Object src, final ZoneId zoneId) { + assertArgumentNotNull("zoneId", zoneId); + if (src == null) { + return null; + } + if (src instanceof LocalDateTime) { + return (LocalDateTime) src; + } + final Instant instant = toEpochInstant(src); + if (instant != null) { + return LocalDateTime.ofInstant(instant, zoneId); + } + final String str = src.toString(); + if (isEmpty(str)) { + return null; + } + try { + return LocalDateTime.parse(str); + } catch (final DateTimeParseException e) { + throw new ParseRuntimeException(str); + } + } + + /** + * Converts the given object to a {@link LocalTime} using the system default time zone. + * + * @param src + * The source object to convert. + * @return The converted {@link LocalTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static LocalTime toLocalTime(final Object src) { + return toLocalTime(src, ZoneId.systemDefault()); + } + + /** + * Converts the given object to a {@link LocalTime}. + * + * @param src + * The source object to convert. + * @param zoneId + * The time zone used when the source is an absolute point on the time line. Must not be {@literal null}. + * @return The converted {@link LocalTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static LocalTime toLocalTime(final Object src, final ZoneId zoneId) { + assertArgumentNotNull("zoneId", zoneId); + if (src == null) { + return null; + } + if (src instanceof LocalTime) { + return (LocalTime) src; + } + final Instant instant = toEpochInstant(src); + if (instant != null) { + return instant.atZone(zoneId).toLocalTime(); + } + final String str = src.toString(); + if (isEmpty(str)) { + return null; + } + try { + return LocalTime.parse(str); + } catch (final DateTimeParseException e) { + throw new ParseRuntimeException(str); + } + } + + /** + * Converts the given object to an {@link Instant}. + *

+ * An {@link Instant} is an absolute point on the time line, so no time zone is required. + *

+ * + * @param src + * The source object to convert. + * @return The converted {@link Instant}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static Instant toInstant(final Object src) { + if (src == null) { + return null; + } + final Instant instant = toEpochInstant(src); + if (instant != null) { + return instant; + } + final String str = src.toString(); + if (isEmpty(str)) { + return null; + } + try { + return Instant.parse(str); + } catch (final DateTimeParseException e) { + throw new ParseRuntimeException(str); + } + } + + /** + * Converts the given object to an {@link OffsetDateTime} using the system default time zone. + * + * @param src + * The source object to convert. + * @return The converted {@link OffsetDateTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static OffsetDateTime toOffsetDateTime(final Object src) { + return toOffsetDateTime(src, ZoneId.systemDefault()); + } + + /** + * Converts the given object to an {@link OffsetDateTime}. + * + * @param src + * The source object to convert. + * @param zoneId + * The time zone used when the source is an absolute point on the time line. Must not be {@literal null}. + * @return The converted {@link OffsetDateTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static OffsetDateTime toOffsetDateTime(final Object src, final ZoneId zoneId) { + assertArgumentNotNull("zoneId", zoneId); + if (src == null) { + return null; + } + if (src instanceof OffsetDateTime) { + return (OffsetDateTime) src; + } + final Instant instant = toEpochInstant(src); + if (instant != null) { + return OffsetDateTime.ofInstant(instant, zoneId); + } + final String str = src.toString(); + if (isEmpty(str)) { + return null; + } + try { + return OffsetDateTime.parse(str); + } catch (final DateTimeParseException e) { + throw new ParseRuntimeException(str); + } + } + + /** + * Converts the given object to a {@link ZonedDateTime} using the system default time zone. + * + * @param src + * The source object to convert. + * @return The converted {@link ZonedDateTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static ZonedDateTime toZonedDateTime(final Object src) { + return toZonedDateTime(src, ZoneId.systemDefault()); + } + + /** + * Converts the given object to a {@link ZonedDateTime}. + * + * @param src + * The source object to convert. + * @param zoneId + * The time zone used when the source is an absolute point on the time line. Must not be {@literal null}. + * @return The converted {@link ZonedDateTime}, or {@literal null} if the source is {@literal null} or an empty string. + */ + public static ZonedDateTime toZonedDateTime(final Object src, final ZoneId zoneId) { + assertArgumentNotNull("zoneId", zoneId); + if (src == null) { + return null; + } + if (src instanceof ZonedDateTime) { + return (ZonedDateTime) src; + } + final Instant instant = toEpochInstant(src); + if (instant != null) { + return ZonedDateTime.ofInstant(instant, zoneId); + } + final String str = src.toString(); + if (isEmpty(str)) { + return null; + } + try { + return ZonedDateTime.parse(str); + } catch (final DateTimeParseException e) { + throw new ParseRuntimeException(str); + } + } + + /** + * Returns the {@link Instant} for a source object that represents an absolute point on the time line. + *

+ * Handles {@link Instant}, {@link Timestamp} (preserving nanosecond precision), {@link Date} (via its millisecond value, which is safe + * for {@link java.sql.Date} and {@link java.sql.Time} whose {@code toInstant} is unsupported), {@link Calendar}, and {@link Number} + * (interpreted as epoch milliseconds). Returns {@literal null} for any other type, including {@link String}, so the caller can fall + * back to string parsing. + *

+ * + * @param src + * The source object. Must not be {@literal null}. + * @return The corresponding {@link Instant}, or {@literal null} if the source does not represent an absolute point on the time line. + */ + protected static Instant toEpochInstant(final Object src) { + if (src instanceof Instant) { + return (Instant) src; + } + if (src instanceof Timestamp) { + return ((Timestamp) src).toInstant(); + } + if (src instanceof Date) { + return Instant.ofEpochMilli(((Date) src).getTime()); + } + if (src instanceof Calendar) { + return ((Calendar) src).toInstant(); + } + if (src instanceof Number) { + return Instant.ofEpochMilli(((Number) src).longValue()); + } + return null; + } + +} diff --git a/src/main/java/org/codelibs/core/crypto/CachedCipher.java b/src/main/java/org/codelibs/core/crypto/CachedCipher.java index fcd561a..038e8d2 100644 --- a/src/main/java/org/codelibs/core/crypto/CachedCipher.java +++ b/src/main/java/org/codelibs/core/crypto/CachedCipher.java @@ -15,10 +15,14 @@ */ package org.codelibs.core.crypto; +import static org.codelibs.core.misc.AssertionUtil.assertArgumentNotNull; + import java.io.UnsupportedEncodingException; +import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; @@ -26,11 +30,13 @@ import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.codelibs.core.CoreLibConstants; import org.codelibs.core.exception.BadPaddingRuntimeException; import org.codelibs.core.exception.IllegalBlockSizeRuntimeException; +import org.codelibs.core.exception.InvalidAlgorithmParameterRuntimeException; import org.codelibs.core.exception.InvalidKeyRuntimeException; import org.codelibs.core.exception.NoSuchAlgorithmRuntimeException; import org.codelibs.core.exception.NoSuchPaddingRuntimeException; @@ -96,6 +102,18 @@ public CachedCipher() { private static final String AES = "AES"; + /** Transformation used by the authenticated {@link #encryptWithIv}/{@link #decryptWithIv} API. */ + private static final String AES_GCM_TRANSFORMATION = "AES/GCM/NoPadding"; + + /** Standard GCM nonce length in bytes. */ + private static final int GCM_IV_LENGTH = 12; + + /** GCM authentication tag length in bits. */ + private static final int GCM_TAG_LENGTH_BITS = 128; + + /** Secure source of randomness for IV generation. */ + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + /** * The algorithm to use for the cipher. * Default is Blowfish for backward compatibility. @@ -335,6 +353,92 @@ public String decryptoText(final String text) { return decryptText(text); } + /** + * Encrypts data using AES in GCM mode (authenticated encryption) with a freshly generated + * random IV. The 12-byte IV is prepended to the returned value, followed by the ciphertext + * and the GCM authentication tag. + *

+ * This is an opt-in, self-contained alternative to the pooled {@code encrypt}/{@code decrypt} + * methods (which default to Blowfish in ECB mode and cannot carry an IV). It generates a + * unique nonce per call and does not reuse or affect the cipher pool, so it is safe for + * confidential data. The instance-level configuration ({@link #setKey(String)}, + * {@link #setAlgorithm(String)}, {@link #setTransformation(String)}) is not used; the caller + * supplies the AES {@link Key} directly. + *

+ * + * @param data + * the plaintext to encrypt. Must not be {@literal null}. + * @param key + * the AES key. Must not be {@literal null}. + * @return the 12-byte IV followed by the ciphertext and GCM tag + */ + public byte[] encryptWithIv(final byte[] data, final Key key) { + assertArgumentNotNull("data", data); + assertArgumentNotNull("key", key); + + final byte[] iv = new byte[GCM_IV_LENGTH]; + SECURE_RANDOM.nextBytes(iv); + try { + final Cipher cipher = Cipher.getInstance(AES_GCM_TRANSFORMATION); + cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_LENGTH_BITS, iv)); + final byte[] encrypted = cipher.doFinal(data); + final byte[] result = new byte[iv.length + encrypted.length]; + System.arraycopy(iv, 0, result, 0, iv.length); + System.arraycopy(encrypted, 0, result, iv.length, encrypted.length); + return result; + } catch (final NoSuchAlgorithmException e) { + throw new NoSuchAlgorithmRuntimeException(e); + } catch (final NoSuchPaddingException e) { + throw new NoSuchPaddingRuntimeException(e); + } catch (final InvalidKeyException e) { + throw new InvalidKeyRuntimeException(e); + } catch (final InvalidAlgorithmParameterException e) { + throw new InvalidAlgorithmParameterRuntimeException(e); + } catch (final IllegalBlockSizeException e) { + throw new IllegalBlockSizeRuntimeException(e); + } catch (final BadPaddingException e) { + throw new BadPaddingRuntimeException(e); + } + } + + /** + * Decrypts data produced by {@link #encryptWithIv(byte[], Key)}. The 12-byte IV is read from + * the front of {@code data} and the remaining bytes are decrypted and authenticated. + * + * @param data + * the IV followed by the ciphertext and GCM tag. Must not be {@literal null}. + * @param key + * the AES key. Must not be {@literal null}. + * @return the decrypted plaintext + */ + public byte[] decryptWithIv(final byte[] data, final Key key) { + assertArgumentNotNull("data", data); + assertArgumentNotNull("key", key); + if (data.length <= GCM_IV_LENGTH) { + throw new IllegalBlockSizeRuntimeException(new IllegalBlockSizeException("Encrypted data is too short to contain an IV.")); + } + + final byte[] iv = new byte[GCM_IV_LENGTH]; + System.arraycopy(data, 0, iv, 0, GCM_IV_LENGTH); + try { + final Cipher cipher = Cipher.getInstance(AES_GCM_TRANSFORMATION); + cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(GCM_TAG_LENGTH_BITS, iv)); + return cipher.doFinal(data, GCM_IV_LENGTH, data.length - GCM_IV_LENGTH); + } catch (final NoSuchAlgorithmException e) { + throw new NoSuchAlgorithmRuntimeException(e); + } catch (final NoSuchPaddingException e) { + throw new NoSuchPaddingRuntimeException(e); + } catch (final InvalidKeyException e) { + throw new InvalidKeyRuntimeException(e); + } catch (final InvalidAlgorithmParameterException e) { + throw new InvalidAlgorithmParameterRuntimeException(e); + } catch (final IllegalBlockSizeException e) { + throw new IllegalBlockSizeRuntimeException(e); + } catch (final BadPaddingException e) { + throw new BadPaddingRuntimeException(e); + } + } + /** * Polls an encryption cipher from the queue, creating a new one if none are available. * diff --git a/src/main/java/org/codelibs/core/exception/InvalidAlgorithmParameterRuntimeException.java b/src/main/java/org/codelibs/core/exception/InvalidAlgorithmParameterRuntimeException.java new file mode 100644 index 0000000..1dfada5 --- /dev/null +++ b/src/main/java/org/codelibs/core/exception/InvalidAlgorithmParameterRuntimeException.java @@ -0,0 +1,41 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.exception; + +import static org.codelibs.core.collection.ArrayUtil.asArray; + +import java.security.InvalidAlgorithmParameterException; + +/** + * Exception that wraps {@link InvalidAlgorithmParameterException}. + * + * @author shinsuke + */ +public class InvalidAlgorithmParameterRuntimeException extends ClRuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Creates a {@link InvalidAlgorithmParameterRuntimeException}. + * + * @param cause + * The cause of the exception + */ + public InvalidAlgorithmParameterRuntimeException(final InvalidAlgorithmParameterException cause) { + super("ECL0117", asArray(cause), cause); + } + +} diff --git a/src/main/java/org/codelibs/core/io/CloseableUtil.java b/src/main/java/org/codelibs/core/io/CloseableUtil.java index 99bd052..bc49321 100644 --- a/src/main/java/org/codelibs/core/io/CloseableUtil.java +++ b/src/main/java/org/codelibs/core/io/CloseableUtil.java @@ -20,6 +20,7 @@ import java.io.Closeable; import java.io.IOException; +import org.codelibs.core.exception.IORuntimeException; import org.codelibs.core.log.Logger; /** @@ -83,4 +84,28 @@ public static void closeQuietly(final Closeable closeable) { // ignore } } + + /** + * Closes a {@link Closeable}, propagating any {@link IOException} wrapped in an + * {@link IORuntimeException}. + *

+ * Unlike {@link #close(Closeable)} and {@link #closeQuietly(Closeable)}, this method does not + * suppress the exception. Use it for output streams and writers, where a failure during + * {@link Closeable#close()} (which performs the final flush) means the data was not fully + * written and must not be silently ignored. + *

+ * + * @param closeable the closeable object + * @throws IORuntimeException if {@link Closeable#close()} throws an {@link IOException} + */ + public static void closeAndRethrow(final Closeable closeable) { + if (closeable == null) { + return; + } + try { + closeable.close(); + } catch (final IOException e) { + throw new IORuntimeException(e); + } + } } diff --git a/src/main/java/org/codelibs/core/io/FileUtil.java b/src/main/java/org/codelibs/core/io/FileUtil.java index 5e250d7..1dd2c6e 100644 --- a/src/main/java/org/codelibs/core/io/FileUtil.java +++ b/src/main/java/org/codelibs/core/io/FileUtil.java @@ -103,6 +103,39 @@ public static boolean isPathSafe(final Path pathToCheck, final Path baseDirector return normalizedPath.startsWith(normalizedBase); } + /** + * Validates that a given path is within the base directory after resolving symbolic links. + *

+ * Unlike {@link #isPathSafe(Path, Path)}, which performs only lexical normalization, this + * method resolves symbolic links via {@link Path#toRealPath(java.nio.file.LinkOption...)}. + * A symbolic link located inside {@code baseDirectory} that points outside of it is therefore + * correctly rejected, making this the stronger choice when the file system may contain links. + *

+ *

+ * Note: {@code toRealPath} requires the paths to exist. If either + * {@code pathToCheck} or {@code baseDirectory} does not exist, or an I/O error occurs while + * resolving them, this method returns {@code false}. To validate a path that has not been + * created yet, resolve the nearest existing ancestor with {@code toRealPath} yourself and + * pass the result here. + *

+ * + * @param pathToCheck the path to validate (must not be {@literal null}) + * @param baseDirectory the base directory that the path must be within (must not be {@literal null}) + * @return true if the resolved real path is within the resolved base directory, false otherwise + */ + public static boolean isRealPathSafe(final Path pathToCheck, final Path baseDirectory) { + assertArgumentNotNull("pathToCheck", pathToCheck); + assertArgumentNotNull("baseDirectory", baseDirectory); + + try { + final Path realBase = baseDirectory.toRealPath(); + final Path realPath = pathToCheck.toRealPath(); + return realPath.startsWith(realBase); + } catch (final IOException e) { + return false; + } + } + /** * Validates that a given file is safe and does not attempt path traversal attacks. *

diff --git a/src/main/resources/CLMessages.properties b/src/main/resources/CLMessages.properties index cef2183..4f9e6e1 100644 --- a/src/main/resources/CLMessages.properties +++ b/src/main/resources/CLMessages.properties @@ -56,6 +56,7 @@ ECL0113=NoSuchPaddingException occurred, because {0} ECL0114=NoSuchAlgorithmException occurred, because {0} ECL0115=Failed to set accessible to the field: {0} ECL0116=Failed to set accessible to the method: {0} +ECL0117=InvalidAlgorithmParameterException occurred, because {0} WCL0013=Protocol of URL({1}) corresponding to route package({0}) is unknown. WCL0014=resource corresponding to route package({0}) was not found from the class path. diff --git a/src/test/java/org/codelibs/core/beans/impl/RecordBeanDescTest.java b/src/test/java/org/codelibs/core/beans/impl/RecordBeanDescTest.java new file mode 100644 index 0000000..fa25e07 --- /dev/null +++ b/src/test/java/org/codelibs/core/beans/impl/RecordBeanDescTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.beans.impl; + +import static org.codelibs.core.TestUtil.sameClass; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import org.codelibs.core.beans.BeanDesc; +import org.codelibs.core.beans.PropertyDesc; +import org.codelibs.core.beans.factory.BeanDescFactory; +import org.junit.Test; + +/** + * Tests {@link BeanDescImpl} support for Java {@link Record} types. + */ +public class RecordBeanDescTest { + + /** A record with primitive components. */ + public record Point(int x, int y) { + } + + /** A record mixing a reference-type component and a primitive component. */ + public record Person(String name, int age) { + } + + /** A conventional JavaBean used to confirm non-record behavior is unchanged. */ + public static class Hello { + private String message; + + public String getMessage() { + return message; + } + + public void setMessage(final String message) { + this.message = message; + } + } + + /** + * Record accessors ({@code name()} form, without get/is/set prefixes) are detected as read-only properties. + */ + @Test + public void testRecordPropertyDetection() throws Exception { + final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(Point.class); + // Only x and y; the record branch must not double-register alongside the get/is/set scan. + assertThat(beanDesc.getPropertyDescSize(), is(2)); + + final PropertyDesc x = beanDesc.getPropertyDesc("x"); + assertThat(x.getPropertyName(), is("x")); + assertThat(x.getPropertyType(), is(sameClass(int.class))); + assertThat(x.getReadMethod(), is(notNullValue())); + assertThat(x.getReadMethod().getName(), is("x")); + assertThat(x.getWriteMethod(), is(nullValue())); + assertThat(x.isReadable(), is(true)); + assertThat(x.isWritable(), is(false)); + assertThat(x.hasWriteMethod(), is(false)); + + assertThat(beanDesc.hasPropertyDesc("y"), is(true)); + } + + /** + * The property value is read through the record accessor. + */ + @Test + public void testRecordGetValue() throws Exception { + final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(Point.class); + final Point point = new Point(10, 20); + assertThat(beanDesc.getPropertyDesc("x").getValue(point), is(10)); + assertThat(beanDesc.getPropertyDesc("y").getValue(point), is(20)); + } + + /** + * A record component of reference type is read correctly. + */ + @Test + public void testRecordReferenceComponent() throws Exception { + final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(Person.class); + final PropertyDesc name = beanDesc.getPropertyDesc("name"); + assertThat(name.getPropertyType(), is(sameClass(String.class))); + final Person person = new Person("Alice", 30); + assertThat(name.getValue(person), is("Alice")); + assertThat(beanDesc.getPropertyDesc("age").getValue(person), is(30)); + } + + /** + * A record is instantiated through its canonical constructor, which is discovered via the existing + * constructor scan; arguments are matched in declaration order. + */ + @Test + public void testRecordNewInstance() throws Exception { + final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(Point.class); + final Point point = beanDesc.newInstance(3, 4); + assertThat(point, is(notNullValue())); + assertThat(point.x(), is(3)); + assertThat(point.y(), is(4)); + } + + /** + * A conventional JavaBean with getter/setter continues to expose a readable and writable property. + */ + @Test + public void testRegularBeanUnchanged() throws Exception { + final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(Hello.class); + final PropertyDesc message = beanDesc.getPropertyDesc("message"); + assertThat(message.getPropertyType(), is(sameClass(String.class))); + assertThat(message.getReadMethod(), is(notNullValue())); + assertThat(message.getWriteMethod(), is(notNullValue())); + assertThat(message.isReadable(), is(true)); + assertThat(message.isWritable(), is(true)); + + final Hello hello = new Hello(); + message.setValue(hello, "world"); + assertThat(message.getValue(hello), is("world")); + } +} diff --git a/src/test/java/org/codelibs/core/convert/TemporalConversionUtilTest.java b/src/test/java/org/codelibs/core/convert/TemporalConversionUtilTest.java new file mode 100644 index 0000000..aedf083 --- /dev/null +++ b/src/test/java/org/codelibs/core/convert/TemporalConversionUtilTest.java @@ -0,0 +1,496 @@ +/* + * Copyright 2012-2025 CodeLibs Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.codelibs.core.convert; + +import static org.codelibs.core.convert.TemporalConversionUtil.toInstant; +import static org.codelibs.core.convert.TemporalConversionUtil.toLocalDate; +import static org.codelibs.core.convert.TemporalConversionUtil.toLocalDateTime; +import static org.codelibs.core.convert.TemporalConversionUtil.toLocalTime; +import static org.codelibs.core.convert.TemporalConversionUtil.toOffsetDateTime; +import static org.codelibs.core.convert.TemporalConversionUtil.toZonedDateTime; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; + +import org.codelibs.core.exception.NullArgumentException; +import org.codelibs.core.exception.ParseRuntimeException; +import org.junit.Test; + +/** + * @author shinsuke + */ +public class TemporalConversionUtilTest { + + /** Fixed reference instant used across the tests: 2010-09-07T06:05:04Z. */ + private static final Instant INSTANT = Instant.parse("2010-09-07T06:05:04Z"); + + /** Epoch milliseconds of {@link #INSTANT}. */ + private static final long MILLIS = INSTANT.toEpochMilli(); + + /** Fixed time zone used to keep zone-dependent assertions environment independent. */ + private static final ZoneId UTC = ZoneOffset.UTC; + + // ----------------------------------------------------------------- + // toLocalDate + // ----------------------------------------------------------------- + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_Null() throws Exception { + assertThat(toLocalDate(null), is(nullValue())); + assertThat(toLocalDate(null, UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_EmptyString() throws Exception { + assertThat(toLocalDate("", UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_Passthrough() throws Exception { + final LocalDate src = LocalDate.of(2010, 9, 7); + assertThat(toLocalDate(src, UTC), is(src)); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_Date() throws Exception { + assertThat(toLocalDate(new Date(MILLIS), UTC), is(LocalDate.of(2010, 9, 7))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_EpochMillis() throws Exception { + assertThat(toLocalDate(MILLIS, UTC), is(LocalDate.of(2010, 9, 7))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_String() throws Exception { + assertThat(toLocalDate("2010-09-07", UTC), is(LocalDate.of(2010, 9, 7))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDate_DefaultZone() throws Exception { + assertThat(toLocalDate(new Date(MILLIS)), is(INSTANT.atZone(ZoneId.systemDefault()).toLocalDate())); + } + + /** + * @throws Exception + */ + @Test(expected = ParseRuntimeException.class) + public void testToLocalDate_InvalidString() throws Exception { + toLocalDate("invalid", UTC); + } + + /** + * @throws Exception + */ + @Test(expected = NullArgumentException.class) + public void testToLocalDate_NullZone() throws Exception { + toLocalDate(new Date(MILLIS), null); + } + + // ----------------------------------------------------------------- + // toLocalDateTime + // ----------------------------------------------------------------- + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_Null() throws Exception { + assertThat(toLocalDateTime(null), is(nullValue())); + assertThat(toLocalDateTime(null, UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_EmptyString() throws Exception { + assertThat(toLocalDateTime("", UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_Passthrough() throws Exception { + final LocalDateTime src = LocalDateTime.of(2010, 9, 7, 6, 5, 4); + assertThat(toLocalDateTime(src, UTC), is(src)); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_Date() throws Exception { + assertThat(toLocalDateTime(new Date(MILLIS), UTC), is(LocalDateTime.of(2010, 9, 7, 6, 5, 4))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_EpochMillis() throws Exception { + assertThat(toLocalDateTime(MILLIS, UTC), is(LocalDateTime.of(2010, 9, 7, 6, 5, 4))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_String() throws Exception { + assertThat(toLocalDateTime("2010-09-07T06:05:04", UTC), is(LocalDateTime.of(2010, 9, 7, 6, 5, 4))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalDateTime_DefaultZone() throws Exception { + assertThat(toLocalDateTime(new Date(MILLIS)), is(LocalDateTime.ofInstant(INSTANT, ZoneId.systemDefault()))); + } + + /** + * @throws Exception + */ + @Test(expected = ParseRuntimeException.class) + public void testToLocalDateTime_InvalidString() throws Exception { + toLocalDateTime("invalid", UTC); + } + + // ----------------------------------------------------------------- + // toLocalTime + // ----------------------------------------------------------------- + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_Null() throws Exception { + assertThat(toLocalTime(null), is(nullValue())); + assertThat(toLocalTime(null, UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_EmptyString() throws Exception { + assertThat(toLocalTime("", UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_Passthrough() throws Exception { + final LocalTime src = LocalTime.of(6, 5, 4); + assertThat(toLocalTime(src, UTC), is(src)); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_Date() throws Exception { + assertThat(toLocalTime(new Date(MILLIS), UTC), is(LocalTime.of(6, 5, 4))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_EpochMillis() throws Exception { + assertThat(toLocalTime(MILLIS, UTC), is(LocalTime.of(6, 5, 4))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_String() throws Exception { + assertThat(toLocalTime("06:05:04", UTC), is(LocalTime.of(6, 5, 4))); + } + + /** + * @throws Exception + */ + @Test + public void testToLocalTime_DefaultZone() throws Exception { + assertThat(toLocalTime(new Date(MILLIS)), is(INSTANT.atZone(ZoneId.systemDefault()).toLocalTime())); + } + + /** + * @throws Exception + */ + @Test(expected = ParseRuntimeException.class) + public void testToLocalTime_InvalidString() throws Exception { + toLocalTime("invalid", UTC); + } + + // ----------------------------------------------------------------- + // toInstant + // ----------------------------------------------------------------- + + /** + * @throws Exception + */ + @Test + public void testToInstant_Null() throws Exception { + assertThat(toInstant(null), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_EmptyString() throws Exception { + assertThat(toInstant(""), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_Passthrough() throws Exception { + assertThat(toInstant(INSTANT), is(INSTANT)); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_Date() throws Exception { + assertThat(toInstant(new Date(MILLIS)), is(INSTANT)); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_Calendar() throws Exception { + final Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(MILLIS); + assertThat(toInstant(calendar), is(INSTANT)); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_Timestamp_PreservesNanos() throws Exception { + final Instant withNanos = INSTANT.plusNanos(123456789); + final Timestamp timestamp = Timestamp.from(withNanos); + assertThat(toInstant(timestamp), is(withNanos)); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_EpochMillis() throws Exception { + assertThat(toInstant(MILLIS), is(INSTANT)); + } + + /** + * @throws Exception + */ + @Test + public void testToInstant_String() throws Exception { + assertThat(toInstant("2010-09-07T06:05:04Z"), is(INSTANT)); + } + + /** + * @throws Exception + */ + @Test(expected = ParseRuntimeException.class) + public void testToInstant_InvalidString() throws Exception { + toInstant("invalid"); + } + + // ----------------------------------------------------------------- + // toOffsetDateTime + // ----------------------------------------------------------------- + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_Null() throws Exception { + assertThat(toOffsetDateTime(null), is(nullValue())); + assertThat(toOffsetDateTime(null, UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_EmptyString() throws Exception { + assertThat(toOffsetDateTime("", UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_Passthrough() throws Exception { + final OffsetDateTime src = OffsetDateTime.of(2010, 9, 7, 6, 5, 4, 0, ZoneOffset.UTC); + assertThat(toOffsetDateTime(src, UTC), is(src)); + } + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_Date() throws Exception { + assertThat(toOffsetDateTime(new Date(MILLIS), UTC), is(OffsetDateTime.of(2010, 9, 7, 6, 5, 4, 0, ZoneOffset.UTC))); + } + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_EpochMillis() throws Exception { + assertThat(toOffsetDateTime(MILLIS, UTC), is(OffsetDateTime.of(2010, 9, 7, 6, 5, 4, 0, ZoneOffset.UTC))); + } + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_String() throws Exception { + assertThat(toOffsetDateTime("2010-09-07T06:05:04+00:00", UTC), is(OffsetDateTime.of(2010, 9, 7, 6, 5, 4, 0, ZoneOffset.UTC))); + } + + /** + * @throws Exception + */ + @Test + public void testToOffsetDateTime_DefaultZone() throws Exception { + assertThat(toOffsetDateTime(new Date(MILLIS)), is(OffsetDateTime.ofInstant(INSTANT, ZoneId.systemDefault()))); + } + + /** + * @throws Exception + */ + @Test(expected = ParseRuntimeException.class) + public void testToOffsetDateTime_InvalidString() throws Exception { + toOffsetDateTime("invalid", UTC); + } + + // ----------------------------------------------------------------- + // toZonedDateTime + // ----------------------------------------------------------------- + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_Null() throws Exception { + assertThat(toZonedDateTime(null), is(nullValue())); + assertThat(toZonedDateTime(null, UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_EmptyString() throws Exception { + assertThat(toZonedDateTime("", UTC), is(nullValue())); + } + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_Passthrough() throws Exception { + final ZonedDateTime src = ZonedDateTime.of(2010, 9, 7, 6, 5, 4, 0, UTC); + assertThat(toZonedDateTime(src, UTC), is(src)); + } + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_Date() throws Exception { + assertThat(toZonedDateTime(new Date(MILLIS), UTC), is(ZonedDateTime.ofInstant(INSTANT, UTC))); + } + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_EpochMillis() throws Exception { + assertThat(toZonedDateTime(MILLIS, UTC), is(ZonedDateTime.ofInstant(INSTANT, UTC))); + } + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_String() throws Exception { + assertThat(toZonedDateTime("2010-09-07T06:05:04Z", UTC), is(ZonedDateTime.parse("2010-09-07T06:05:04Z"))); + } + + /** + * @throws Exception + */ + @Test + public void testToZonedDateTime_DefaultZone() throws Exception { + assertThat(toZonedDateTime(new Date(MILLIS)), is(ZonedDateTime.ofInstant(INSTANT, ZoneId.systemDefault()))); + } + + /** + * @throws Exception + */ + @Test(expected = ParseRuntimeException.class) + public void testToZonedDateTime_InvalidString() throws Exception { + toZonedDateTime("invalid", UTC); + } + +} diff --git a/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java b/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java index 4446747..64d3d6c 100644 --- a/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java +++ b/src/test/java/org/codelibs/core/crypto/CachedCipherTest.java @@ -182,6 +182,32 @@ public void testKeyBasedCipherReinitializedPerKey() { assertArrayEquals(data, cipher.decrypt(encB, keyB)); } + @Test + public void testEncryptDecryptWithIv() { + final CachedCipher cipher = new CachedCipher(); + final Key key = new SecretKeySpec("0123456789abcdef".getBytes(), "AES"); + final byte[] original = "Hello World".getBytes(); + + final byte[] encrypted1 = cipher.encryptWithIv(original, key); + final byte[] encrypted2 = cipher.encryptWithIv(original, key); + + // A fresh random IV per call means the same plaintext yields different ciphertext. + assertThat(encrypted1, is(not(encrypted2))); + assertArrayEquals(original, cipher.decryptWithIv(encrypted1, key)); + assertArrayEquals(original, cipher.decryptWithIv(encrypted2, key)); + } + + @Test(expected = org.codelibs.core.exception.BadPaddingRuntimeException.class) + public void testDecryptWithIvRejectsTamperedData() { + final CachedCipher cipher = new CachedCipher(); + final Key key = new SecretKeySpec("0123456789abcdef".getBytes(), "AES"); + final byte[] encrypted = cipher.encryptWithIv("Hello World".getBytes(), key); + + // Flip a bit in the ciphertext; GCM authentication must reject it. + encrypted[encrypted.length - 1] ^= 0x01; + cipher.decryptWithIv(encrypted, key); + } + @Test public void testStringKeyChangeInvalidatesPooledCipher() { // Regression: changing the key on a reused instance must take effect. Before the fix, diff --git a/src/test/java/org/codelibs/core/io/CloseableUtilTest.java b/src/test/java/org/codelibs/core/io/CloseableUtilTest.java index f6f3d9a..163dad0 100644 --- a/src/test/java/org/codelibs/core/io/CloseableUtilTest.java +++ b/src/test/java/org/codelibs/core/io/CloseableUtilTest.java @@ -21,6 +21,7 @@ import java.io.IOException; import java.io.OutputStream; +import org.codelibs.core.exception.IORuntimeException; import org.junit.Test; /** @@ -55,6 +56,32 @@ public void testClose_noThrowIOException() throws Exception { CloseableUtil.close(out); } + /** + * @throws Exception + */ + @Test + public void testCloseAndRethrow() throws Exception { + final NotifyOutputStream out = new NotifyOutputStream(); + CloseableUtil.closeAndRethrow(out); + assertThat(out.getNotify(), is("closed")); + } + + /** + * @throws Exception + */ + @Test + public void testCloseAndRethrowNull() throws Exception { + CloseableUtil.closeAndRethrow((OutputStream) null); + } + + /** + * @throws Exception + */ + @Test(expected = IORuntimeException.class) + public void testCloseAndRethrow_propagatesIOException() throws Exception { + CloseableUtil.closeAndRethrow(new IOExceptionOccurOutputStream()); + } + private static class NotifyOutputStream extends OutputStream { private String notify_; diff --git a/src/test/java/org/codelibs/core/io/FileUtilTest.java b/src/test/java/org/codelibs/core/io/FileUtilTest.java index 4d2b1f1..a49f383 100644 --- a/src/test/java/org/codelibs/core/io/FileUtilTest.java +++ b/src/test/java/org/codelibs/core/io/FileUtilTest.java @@ -79,6 +79,45 @@ public void testIsPathSafe_SafePath() throws Exception { assertTrue("Safe path should be allowed", FileUtil.isPathSafe(safePath, baseDir)); } + /** + * Test isRealPathSafe with an existing file inside the base and a non-existent path. + * + * @throws Exception + */ + @Test + public void testIsRealPathSafe_ExistingInsideAndMissing() throws Exception { + final Path baseDir = tempFolder.getRoot().toPath(); + final File inside = tempFolder.newFile("inside.txt"); + + assertTrue("Existing file inside base should be allowed", FileUtil.isRealPathSafe(inside.toPath(), baseDir)); + assertFalse("Non-existent path should be rejected", FileUtil.isRealPathSafe(baseDir.resolve("missing.txt"), baseDir)); + } + + /** + * Test that isRealPathSafe rejects a symbolic link inside the base that escapes it, + * whereas the lexical isPathSafe is fooled. + * + * @throws Exception + */ + @Test + public void testIsRealPathSafe_SymlinkEscapingBaseIsRejected() throws Exception { + final Path root = tempFolder.getRoot().toPath(); + final Path baseDir = Files.createDirectory(root.resolve("base")); + final Path outsideDir = Files.createDirectory(root.resolve("outside")); + final Path secret = Files.createFile(outsideDir.resolve("secret.txt")); + + final Path link = baseDir.resolve("link"); + try { + Files.createSymbolicLink(link, secret); + } catch (final UnsupportedOperationException | IOException e) { + // Symbolic links may be unsupported (e.g. Windows without privilege); skip the test. + org.junit.Assume.assumeNoException(e); + } + + assertTrue("Lexical check is fooled by the link", FileUtil.isPathSafe(link, baseDir)); + assertFalse("Real-path check resolves the escape", FileUtil.isRealPathSafe(link, baseDir)); + } + /** * Test isPathSafe with path traversal attempt *