diff --git a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java index 7ba48249..13fa1792 100644 --- a/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java +++ b/src/main/java/org/morphix/convert/strategy/FinderPathStrategy.java @@ -12,20 +12,10 @@ */ package org.morphix.convert.strategy; -import static org.morphix.reflection.ExtendedField.of; -import static org.morphix.reflection.JavaModifier.STATIC; - -import java.lang.reflect.Field; import java.util.List; -import java.util.Map; -import org.morphix.lang.collections.Lists; -import org.morphix.reflection.Classes; import org.morphix.reflection.ExtendedField; import org.morphix.reflection.FieldPaths; -import org.morphix.reflection.FieldPaths.Step; -import org.morphix.reflection.FieldPaths.StepKind; -import org.morphix.reflection.Fields; /** * Finds the field in the source by path. @@ -50,59 +40,15 @@ public ExtendedField find(final T source, final List fields, } /** - * Returns the field and the object it corresponds to given its path. + * Returns the first field and its owning object from comma-separated alternative paths. * * @param object type * * @param obj object on which to search - * @param path path to the wanted field (object) + * @param path alternative paths to the wanted field * @return field object pair */ public static ExtendedField getConverterFieldByPathInHierarchy(final T obj, final String path) { - List steps = FieldPaths.parse(path); - if (Lists.isEmpty(steps)) { - return ExtendedField.EMPTY; - } - Field resultField = null; - Object resultObject = obj; - Class currentClass = resultObject.getClass(); - for (Step step : steps) { - if (StepKind.PROPERTY == step.kind()) { - if (null != resultField && null != resultObject) { - resultObject = Fields.IgnoreAccess.get(resultObject, resultField); - } - if (null == resultObject) { - return ExtendedField.EMPTY; - } - currentClass = Classes.getFrom(resultObject); - resultField = Fields.getOneDeclaredInHierarchy(currentClass, step.selector()); - if (null != resultField && STATIC.isPresentOn(resultField)) { - return ExtendedField.EMPTY; - } - if (null == resultField && resultObject instanceof Map map) { - if (!map.containsKey(step.selector())) { - return ExtendedField.EMPTY; - } - resultObject = map.get(step.selector()); - continue; - } - if (null == resultField) { - return ExtendedField.EMPTY; - } - } else { - if (null != resultField && null != resultObject) { - resultObject = Fields.IgnoreAccess.get(resultObject, resultField); - } - resultObject = FieldPaths.navigate(resultObject, step); - resultField = null; - if (null == resultObject) { - return ExtendedField.EMPTY; - } - } - } - if (null == resultObject || null == resultField) { - return ExtendedField.EMPTY; - } - return of(resultField, resultObject); + return FieldPaths.resolveField(obj, path); } } diff --git a/src/main/java/org/morphix/reflection/FieldPathParser.java b/src/main/java/org/morphix/reflection/FieldPathParser.java new file mode 100644 index 00000000..3ad91e2f --- /dev/null +++ b/src/main/java/org/morphix/reflection/FieldPathParser.java @@ -0,0 +1,298 @@ +/* + * Copyright 2026 the original author or authors. + * + * 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 + * + * https://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.morphix.reflection; + +import static org.morphix.reflection.JavaModifier.STATIC; + +import java.lang.reflect.Field; +import java.util.Map; + +/** + * Cursor-based field path parser. Each selector is resolved as it is consumed, without allocating tokens or splitting + * the expression into strings. The same parser handles single paths and comma-separated alternatives. + * + * @author Radu Sebastian LAZIN + */ +final class FieldPathParser { + + private final String paths; + + private final int length; + + private final boolean alternatives; + + private final boolean findField; + + private int index; + + private boolean invalid; + + FieldPathParser(final String paths, final boolean alternatives, final boolean findField) { + this.paths = paths; + this.length = paths.length(); + this.alternatives = alternatives; + this.findField = findField; + } + + /** + * Resolves paths in order, stopping at the first match. A malformed alternative can be skipped if its end is + * unambiguous. An unterminated bracket or quoted selector consumes the remainder of the expression. + * + * @param root root object + * @return resolved value or extended field, or null + */ + Object resolve(final Object root) { + while (hasNext()) { + if (alternatives) { + skipWhitespace(); + if (consume(',')) { + continue; + } + } + if (!hasNext()) { + break; + } + invalid = false; + Object result = readPath(root); + if (!alternatives) { + return !invalid && !hasNext() ? result : null; + } + skipWhitespace(); + if (hasNext() && ',' != peek()) { + invalid = true; + skipInvalidPath(); + } + if (!invalid && null != result) { + return result; + } + consume(','); + } + return null; + } + + private Object readPath(final Object root) { + Object value = root; + if ('[' != peek()) { + value = readProperty(value); + } + while (hasNext() && !invalid) { + if (consume('[')) { + value = readBracket(value); + } else if (consume('.')) { + value = readProperty(value); + } else { + break; + } + } + return invalid ? null : value; + } + + private Object readProperty(final Object obj) { + int start = index; + while (hasNext() && !isPropertyDelimiter(peek())) { + ++index; + } + int end = index; + if (alternatives && (!hasNext() || ',' == peek())) { + end = trimEnd(start, end); + } + if (start == end) { + return fail(); + } + if (null == obj) { + return null; + } + String name = paths.substring(start, end); + if (!findField) { + return FieldPaths.readProperty(obj, name); + } + if (obj instanceof Map map) { + return atPathEnd() ? null : map.get(name); + } + Field field = Fields.Unchecked.getOneDeclaredInHierarchy(Classes.getFrom(obj), name); + if (null == field) { + return null; + } + if (STATIC.isPresentOn(field)) { + return null; + } + if (atPathEnd()) { + return ExtendedField.of(field, obj); + } + return Fields.IgnoreAccess.get(obj, field); + } + + private Object readBracket(final Object obj) { + if (!hasNext()) { + return fail(); + } + char ch = peek(); + Object value; + if (isQuote(ch)) { + ++index; + String key = readQuoted(ch); + if (invalid) { + return null; + } + if (!consume(']')) { + skipBracket(); + return fail(); + } + value = FieldPaths.readMapKey(obj, key); + } else { + int start = index; + boolean numeric = true; + while (hasNext() && ']' != peek()) { + ch = peek(); + if ('[' == ch || isQuote(ch)) { + skipBracket(); + return fail(); + } + numeric &= Character.isDigit(ch); + ++index; + } + int end = index; + if (!consume(']') || start == end) { + return fail(); + } + if (numeric) { + try { + int elementIndex = Integer.parseInt(paths, start, end, 10); + value = FieldPaths.readIndex(obj, elementIndex); + } catch (NumberFormatException e) { + return fail(); + } + } else { + value = FieldPaths.readMapKey(obj, paths.substring(start, end)); + } + } + return findField && atPathEnd() ? null : value; + } + + private String readQuoted(final char quote) { + int start = index; + StringBuilder builder = null; + while (hasNext()) { + char ch = peek(); + if (quote == ch) { + String key = null == builder ? paths.substring(start, index) : builder.append(paths, start, index).toString(); + ++index; + return key; + } + if ('\\' == ch) { + if (null == builder) { + builder = new StringBuilder(); + } + builder.append(paths, start, index); + ++index; + if (!hasNext()) { + invalid = true; + return null; + } + builder.append(peek()); + start = index + 1; + } + ++index; + } + invalid = true; + return null; + } + + /** + * Recovers at a top-level comma, using the same quote and bracket rules as normal parsing. + */ + private void skipInvalidPath() { + while (hasNext() && ',' != peek()) { + if (consume('[')) { + skipBracket(); + } else { + ++index; + } + } + } + + /** + * Consumes the remainder of a bracket, including nested malformed brackets and quoted selectors. + */ + private void skipBracket() { + int depth = 1; + while (hasNext() && 0 < depth) { + char ch = peek(); + ++index; + if (isQuote(ch)) { + readQuoted(ch); + } else if ('[' == ch) { + ++depth; + } else if (']' == ch) { + --depth; + } + } + } + + private boolean atPathEnd() { + if (!hasNext()) { + return true; + } + if (!alternatives) { + return false; + } + int end = index; + while (end < length && paths.charAt(end) <= ' ') { + ++end; + } + return end == length || ',' == paths.charAt(end); + } + + private boolean isPropertyDelimiter(final char ch) { + return '.' == ch || '[' == ch || ']' == ch || (alternatives && ',' == ch); + } + + private static boolean isQuote(final char ch) { + return '\'' == ch || '"' == ch; + } + + private boolean hasNext() { + return index < length; + } + + private char peek() { + return paths.charAt(index); + } + + private boolean consume(final char ch) { + if (hasNext() && ch == peek()) { + ++index; + return true; + } + return false; + } + + private void skipWhitespace() { + while (hasNext() && peek() <= ' ') { + ++index; + } + } + + private int trimEnd(final int start, final int end) { + int result = end; + while (start < result && paths.charAt(result - 1) <= ' ') { + --result; + } + return result; + } + + private Object fail() { + invalid = true; + return null; + } +} diff --git a/src/main/java/org/morphix/reflection/FieldPaths.java b/src/main/java/org/morphix/reflection/FieldPaths.java index 5c76742c..b4d1039f 100644 --- a/src/main/java/org/morphix/reflection/FieldPaths.java +++ b/src/main/java/org/morphix/reflection/FieldPaths.java @@ -13,340 +13,111 @@ package org.morphix.reflection; import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.util.ArrayList; import java.util.List; import java.util.Map; import org.morphix.lang.JavaObjects; -import org.morphix.lang.collections.Lists; /** - * Parses and resolves JSON Path-style selectors for field and container access (properties, array or list indices, and - * map keys). + * Resolves field paths using dot notation for properties and bracket notation for array/list indices and map keys. + * Multiple paths can be separated by commas outside bracket selectors. * * @author Radu Sebastian LAZIN */ public interface FieldPaths { /** - * Kind of path step. - */ - enum StepKind { - - /** - * A property or map key accessed with dot notation. - */ - PROPERTY, - - /** - * A zero-based index into an array or list. - */ - INDEX, - - /** - * A map key from bracket notation. - */ - KEY - } - - /** - * One step in a path expression. + * Resolves a single path to its value. + * + * @param value type * - * @param kind step kind - * @param selector property name, index text, or map key + * @param root root object + * @param path field path + * @return value or null if the path cannot be resolved */ - record Step(StepKind kind, String selector) { - // empty + static U resolveValue(final Object root, final String path) { + return JavaObjects.cast(resolve(root, path, false, false)); } /** - * Resolves the value at the given path starting from {@code root}, using the same rules as - * {@link Fields.Safe#getByPath(Object, String)}. + * Resolves the first non-null value in a comma-separated list of paths. Empty alternatives are ignored. * * @param value type * - * @param root start object - * @param path path expression - * @return value at the path, or {@code null} if the path is empty, invalid, or not found + * @param root root object + * @param paths alternative field paths + * @return first non-null value or null */ - static U resolveValue(final Object root, final String path) { - List steps = parse(path); - if (Lists.isEmpty(steps)) { - return null; - } - Object current = root; - for (Step step : steps) { - current = navigate(current, step); - if (null == current) { - break; - } - } - return JavaObjects.cast(current); + static U resolveValues(final Object root, final String paths) { + return JavaObjects.cast(resolve(root, paths, true, false)); } /** - * Parses a path into steps. Returns an empty list for an empty path, or {@code null} when the expression is invalid. + * Finds the first non-static reflective field and its owning object in a comma-separated list of paths. The final field + * is not read; a field with a null value can therefore be found. Paths ending at a container element rather than a + * reflective field are not matches. * - * @param path path expression - * @return parsed steps, empty list for {@code ""}, or {@code null} if invalid + * @param root root object + * @param paths alternative field paths + * @return field and its owning object, or {@link ExtendedField#EMPTY} */ - static List parse(final String path) { - if (path.isEmpty()) { - return List.of(); - } - List steps = new ArrayList<>(); - int index = 0; - int length = path.length(); - while (index < length) { - if (path.charAt(index) == '.') { - return null; - } - int propertyStart = index; - while (index < length) { - char ch = path.charAt(index); - if (ch == '.' || ch == '[') { - break; - } - index++; - } - if (propertyStart < index) { - steps.add(new Step(StepKind.PROPERTY, path.substring(propertyStart, index))); - } - index = parseBracketSteps(path, index, length, steps); - if (index < 0) { - return null; - } - if (index < length) { - if (path.charAt(index) != '.') { - return null; - } - index++; - if (index >= length) { - steps.add(new Step(StepKind.PROPERTY, "")); - return steps; - } - } - } - return steps; + static ExtendedField resolveField(final Object root, final String paths) { + ExtendedField field = JavaObjects.cast(resolve(root, paths, true, true)); + return null == field ? ExtendedField.EMPTY : field; } - /** - * Splits a comma-separated list of paths, ignoring commas inside {@code [...]} segments. - * - * @param paths comma-separated path expressions - * @return trimmed non-empty paths, or an empty list when nothing remains after trimming - */ - static List split(final String paths) { - if (paths.isEmpty()) { - return List.of(); - } - List result = new ArrayList<>(); - StringBuilder current = new StringBuilder(); - int bracketDepth = 0; - boolean inSingleQuote = false; - boolean inDoubleQuote = false; - for (int i = 0; i < paths.length(); ++i) { - char ch = paths.charAt(i); - if (inSingleQuote) { - current.append(ch); - if (ch == '\'' && (i == 0 || paths.charAt(i - 1) != '\\')) { - inSingleQuote = false; - } - continue; - } - if (inDoubleQuote) { - current.append(ch); - if (ch == '"' && (i == 0 || paths.charAt(i - 1) != '\\')) { - inDoubleQuote = false; - } - continue; - } - if (ch == '\'') { - inSingleQuote = true; - current.append(ch); - continue; - } - if (ch == '"') { - inDoubleQuote = true; - current.append(ch); - continue; - } - if (ch == '[') { - bracketDepth++; - current.append(ch); - continue; - } - if (ch == ']') { - bracketDepth--; - current.append(ch); - continue; - } - if (ch == ',' && bracketDepth == 0) { - String path = current.toString().trim(); - if (!path.isEmpty()) { - result.add(path); - } - current.setLength(0); - continue; - } - current.append(ch); - } - String path = current.toString().trim(); - if (!path.isEmpty()) { - result.add(path); + private static Object resolve(final Object root, final String paths, final boolean alternatives, final boolean findField) { + if (null == root || null == paths || paths.isEmpty()) { + return null; } - return result; + return new FieldPathParser(paths, alternatives, findField).resolve(root); } /** - * Applies a single step to the current value. + * Reads a property, treating maps as containers rather than reflective objects. * - * @param current current value - * @param step step to apply - * @return next value, or {@code null} if navigation fails - */ - static Object navigate(final Object current, final Step step) { - return switch (step.kind()) { - case PROPERTY -> readProperty(current, step.selector()); - case INDEX -> readIndex(current, step.selector()); - case KEY -> readMapKey(current, step.selector()); - }; - } - - /** - * @see StepKind#PROPERTY + * @param obj owning object + * @param name property name + * @return value or null */ - static Object readProperty(final Object current, final String propertyName) { - if (null == current || null == propertyName || propertyName.isEmpty()) { + static Object readProperty(final Object obj, final String name) { + if (null == obj || null == name || name.isEmpty()) { return null; } - Class cls = Classes.getFrom(current); - Field field = Fields.Unchecked.getOneDeclaredInHierarchy(cls, propertyName); - if (null != field) { - return Fields.Safe.get(current, field); - } - if (current instanceof Map map) { - return map.get(propertyName); - } - return null; + return obj instanceof Map map ? map.get(name) : Fields.Safe.get(obj, name); } /** - * @see StepKind#INDEX + * Reads a zero-based array or list index. + * + * @param obj container + * @param index element index + * @return element or null */ - static Object readIndex(final Object current, final String indexText) { - if (null == current || null == indexText) { + static Object readIndex(final Object obj, final int index) { + if (null == obj || index < 0) { return null; } - int index; - try { - index = Integer.parseInt(indexText); - } catch (NumberFormatException e) { - return null; - } - if (index < 0) { - return null; - } - if (current instanceof List list) { + if (obj instanceof List list) { return index < list.size() ? list.get(index) : null; } - if (current.getClass().isArray()) { - int length = Array.getLength(current); - return index < length ? Array.get(current, index) : null; + if (obj.getClass().isArray()) { + return index < Array.getLength(obj) ? Array.get(obj, index) : null; } return null; } /** - * @see StepKind#KEY + * Reads a string map key. + * + * @param obj container + * @param key map key + * @return value or null */ - static Object readMapKey(final Object current, final String key) { - if (null == current || null == key) { - return null; - } - if (current instanceof Map map) { + static Object readMapKey(final Object obj, final String key) { + if (null != key && obj instanceof Map map) { return map.get(key); } return null; } - - private static int parseBracketSteps(final String path, final int index, final int length, final List steps) { - int currentIndex = index; - while (currentIndex < length && path.charAt(currentIndex) == '[') { - ++currentIndex; - if (currentIndex >= length) { - return -1; - } - char ch = path.charAt(currentIndex); - if (ch == '\'' || ch == '"') { - int[] nextIndex = new int[1]; - String key = readQuoted(path, currentIndex, length, ch, nextIndex); - if (null == key) { - return -1; - } - steps.add(new Step(StepKind.KEY, key)); - currentIndex = nextIndex[0]; - } else { - int selectorStart = index; - while (currentIndex < length && path.charAt(currentIndex) != ']') { - ++currentIndex; - } - if (currentIndex >= length) { - return -1; - } - String selector = path.substring(selectorStart, currentIndex); - if (selector.isEmpty()) { - return -1; - } - if (isInteger(selector)) { - steps.add(new Step(StepKind.INDEX, selector)); - } else { - steps.add(new Step(StepKind.KEY, selector)); - } - } - if (currentIndex >= length || path.charAt(currentIndex) != ']') { - return -1; - } - ++currentIndex; - } - return currentIndex; - } - - private static boolean isInteger(final String text) { - if (text.isEmpty()) { - return false; - } - for (int i = 0; i < text.length(); ++i) { - if (!Character.isDigit(text.charAt(i))) { - return false; - } - } - return true; - } - - private static String readQuoted(final String path, final int start, final int length, final char quote, final int[] nextIndexOut) { - StringBuilder builder = new StringBuilder(); - int index = start + 1; - while (index < length) { - char ch = path.charAt(index); - if (ch == '\\') { - ++index; - if (index >= length) { - return null; - } - builder.append(path.charAt(index)); - index++; - continue; - } - if (ch == quote) { - ++index; - nextIndexOut[0] = index; - return builder.toString(); - } - builder.append(ch); - ++index; - } - return null; - } } diff --git a/src/main/java/org/morphix/reflection/Fields.java b/src/main/java/org/morphix/reflection/Fields.java index e27cf26e..3168ea76 100644 --- a/src/main/java/org/morphix/reflection/Fields.java +++ b/src/main/java/org/morphix/reflection/Fields.java @@ -822,8 +822,8 @@ static U getByPaths(final T obj, final String... paths) { /** * Variation of {@link Safe#getByPaths(Object, String...)} with paths given as a comma separated list of paths in a - * single string. Each segment is {@linkplain String#trim() trimmed} after splitting on {@code ','}; empty segments are - * ignored. + * single string. Commas inside brackets are part of the selector. Each path is {@linkplain String#trim() trimmed}; + * empty alternatives are ignored. * * @param object type * @param field value type @@ -835,14 +835,7 @@ static U getByPaths(final T obj, final String... paths) { */ static U getByPaths(final T obj, final String paths) { Reflection.requireNotNull(paths, "Cannot resolve field paths: paths are null"); - if (paths.isEmpty()) { - return null; - } - List trimmedPaths = FieldPaths.split(paths); - if (trimmedPaths.isEmpty()) { - return null; - } - return getByPaths(obj, trimmedPaths.toArray(String[]::new)); + return FieldPaths.resolveValues(obj, paths); } /** diff --git a/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java b/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java index b0a40d0b..a38062e0 100644 --- a/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java +++ b/src/test/java/org/morphix/convert/annotation/DeepSourceTest.java @@ -17,6 +17,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.morphix.convert.Conversions.convertFrom; +import java.util.List; +import java.util.Map; + import org.junit.jupiter.api.Test; /** @@ -142,4 +145,36 @@ void shouldDeepConvertStaticStringEvenIfPathMatches() { assertThat(dst.l, nullValue()); assertThat(dst.x, equalTo(TEST_LONG)); } + + public static class IndexedSource { + + List items; + + Map keyed; + } + + public static class IndexedDestination { + + @Src("items[0].s") + Long indexed; + + @Src("items[9].s,keyed['a,b'].s") + Long alternative; + } + + @Test + void shouldDeepConvertIndexedAndAlternativePaths() { + A first = new A(); + first.s = "10"; + A second = new A(); + second.s = "20"; + IndexedSource src = new IndexedSource(); + src.items = List.of(first); + src.keyed = Map.of("a,b", second); + + IndexedDestination dst = convertFrom(src, IndexedDestination::new); + + assertThat(dst.indexed, equalTo(10L)); + assertThat(dst.alternative, equalTo(20L)); + } } diff --git a/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java new file mode 100644 index 00000000..04d15355 --- /dev/null +++ b/src/test/java/org/morphix/convert/strategy/FinderPathStrategyTest.java @@ -0,0 +1,132 @@ +/* + * Copyright 2026 the original author or authors. + * + * 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 + * + * https://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.morphix.convert.strategy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.morphix.reflection.ExtendedField; +import org.morphix.reflection.Fields; + +/** + * Test class for {@link FinderPathStrategy}. + * + * @author Radu Sebastian LAZIN + */ +class FinderPathStrategyTest { + + public static class Entry { + + public static String staticName = "static"; + + @SuppressWarnings("unused") + private String name; + + private Entry(final String name) { + this.name = name; + } + } + + public static class Source { + + private final Entry[] entries = { new Entry("array"), new Entry(null) }; + + private final List items = List.of(new Entry("list")); + + private final Map keyed = Map.of("a,b", new Entry("map"), "key", new Entry("plain")); + + @SuppressWarnings("unused") + private final Entry missing = null; + } + + @Test + void shouldFindFinalFieldAndItsOwnerThroughContainers() { + Source source = new Source(); + FinderPathStrategy strategy = new FinderPathStrategy(); + + assertField(strategy.find(source, List.of(), "entries[0].name"), source.entries[0], "array"); + assertField(strategy.find(source, List.of(), "items[0].name"), source.items.get(0), "list"); + assertField(strategy.find(source, List.of(), "keyed['a,b'].name"), source.keyed.get("a,b"), "map"); + assertField(strategy.find(source, List.of(), "keyed[key].name"), source.keyed.get("key"), "plain"); + assertField(strategy.find(source, List.of(), "keyed.key.name"), source.keyed.get("key"), "plain"); + assertField(strategy.find(source.entries, List.of(), "[0].name"), source.entries[0], "array"); + } + + @Test + void shouldFindFirstExistingFieldAmongAlternatives() { + Source source = new Source(); + ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, + " , missing.name, entries[9].name, keyed['a,b'].name, items[0].name "); + + assertField(field, source.keyed.get("a,b"), "map"); + } + + @Test + void shouldFindNullValuedFieldWithoutTryingFollowingAlternative() { + Source source = new Source(); + String paths = "entries[1].name,items[0].name"; + + ExtendedField field = FinderPathStrategy.getConverterFieldByPathInHierarchy(source, paths); + + assertField(field, source.entries[1], null); + assertThat(Fields.Safe.getByPaths(source, paths), equalTo("list")); + } + + @Test + void shouldRejectStaticFieldsAndContainerElementsAsTerminalFields() { + Source source = new Source(); + + for (String path : List.of("entries[0].staticName", "entries[0]", "keyed['a,b']", "keyed.key", + "missing.name", "entries[0].", "entries[0].name[0]")) { + assertThat(path, FinderPathStrategy.getConverterFieldByPathInHierarchy(source, path), + sameInstance(ExtendedField.EMPTY)); + } + assertThat(FinderPathStrategy.getConverterFieldByPathInHierarchy(null, "entries[0].name"), + sameInstance(ExtendedField.EMPTY)); + assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(source, "entries[0].staticName,items[0].name"), + source.items.get(0), "list"); + assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(source, "entries[0],items[0].name"), + source.items.get(0), "list"); + } + + @Test + void shouldResolveMapKeysInsteadOfInternalFields() { + Map map = new HashMap<>(); + Entry entry = new Entry("map size"); + map.put("size", entry); + + assertField(FinderPathStrategy.getConverterFieldByPathInHierarchy(map, "size.name"), entry, "map size"); + assertThat(FinderPathStrategy.getConverterFieldByPathInHierarchy(map, "size"), + sameInstance(ExtendedField.EMPTY)); + assertThat(Fields.Safe.getByPath(map, "size.name"), equalTo("map size")); + assertThat(Fields.Safe.getByPath(map, "threshold"), nullValue()); + } + + private static void assertField(final ExtendedField field, final Entry owner, final String value) { + assertThat(field.getObject(), sameInstance(owner)); + assertThat(field.getName(), equalTo("name")); + assertThat(field.getField().getDeclaringClass(), equalTo(Entry.class)); + if (null == value) { + assertThat(field.getFieldValue(), nullValue()); + } else { + assertThat(field.getFieldValue(), equalTo(value)); + } + } +} diff --git a/src/test/java/org/morphix/reflection/FieldPathsTest.java b/src/test/java/org/morphix/reflection/FieldPathsTest.java index 6a8269a3..1af42335 100644 --- a/src/test/java/org/morphix/reflection/FieldPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldPathsTest.java @@ -52,40 +52,73 @@ public WithContainers() { } @Test - void shouldParseDotSeparatedProperties() { - List steps = FieldPaths.parse("inner.value"); + void shouldRejectInvalidExpressions() { + WithContainers root = new WithContainers(); - assertThat(steps.size(), equalTo(2)); - assertThat(steps.get(0).kind(), equalTo(FieldPaths.StepKind.PROPERTY)); - assertThat(steps.get(0).selector(), equalTo("inner")); - assertThat(steps.get(1).selector(), equalTo("value")); + for (String path : List.of(".entries", "entries.", "entries..name", "entries.[0]", "entries[0", + "entries[]", "entries[0]]", "entries[0]name", "entries[2147483648]", "entries[0].name,items[0].name")) { + assertThat(path, FieldPaths.resolveValue(root, path), nullValue()); + } } @Test - void shouldParseArrayIndexAndProperty() { - List steps = FieldPaths.parse("entries[0].name"); + void shouldResolveAlternativesWithoutSplittingQuotedKeys() { + WithContainers root = new WithContainers(); - assertThat(steps.size(), equalTo(3)); - assertThat(steps.get(1).kind(), equalTo(FieldPaths.StepKind.INDEX)); - assertThat(steps.get(1).selector(), equalTo("0")); - assertThat(steps.get(2).selector(), equalTo("name")); + assertThat(FieldPaths.resolveValues(root, " , missing.name, items[9].name, data['a,b'], entries[0].name, "), + equalTo("commaKey")); + assertThat(FieldPaths.resolveValues(root, "data['missing,key'], items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, ", ,"), nullValue()); } @Test - void shouldReturnNullForInvalidExpression() { - assertThat(FieldPaths.parse(".inner"), nullValue()); - assertThat(FieldPaths.parse("entries[0"), nullValue()); - assertThat(FieldPaths.parse("entries[]"), nullValue()); + void shouldRecoverFromMalformedAlternatives() { + WithContainers root = new WithContainers(); + + assertThat(FieldPaths.resolveValues(root, ".bad,entries[],entries[0]] ,items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, "entries[2147483648],items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, "data['unterminated,items[0].name"), nullValue()); + assertThat(FieldPaths.resolveValues(root, "items[0].name,entries["), equalTo("fromList")); } @Test - void shouldSplitCommaSeparatedPathsOutsideBrackets() { - List paths = FieldPaths.split("entries[0].name,data['a,b'],items[1].name"); + void shouldResolveEscapedKeysAndFollowingAlternatives() { + WithContainers root = new WithContainers(); + root.data.put("a\\", "backslash"); + root.data.put("a'b", "quote"); + root.data.put("a]b", "bracket"); + root.data.put("", "empty"); + root.data.put("0", "zero"); + root.data.put("a,b", "comma"); + + assertThat(FieldPaths.resolveValue(root, "data['a\\\\']"), equalTo("backslash")); + assertThat(FieldPaths.resolveValues(root, "data['missing\\\\'],items[0].name"), equalTo("fromList")); + assertThat(FieldPaths.resolveValues(root, "data['a\\\\'],items[0].name"), equalTo("backslash")); + assertThat(FieldPaths.resolveValue(root, "data['a\\'b']"), equalTo("quote")); + assertThat(FieldPaths.resolveValue(root, "data[\"a]b\"]"), equalTo("bracket")); + assertThat(FieldPaths.resolveValue(root, "data['']"), equalTo("empty")); + assertThat(FieldPaths.resolveValue(root, "data['0']"), equalTo("zero")); + assertThat(FieldPaths.resolveValue(root, "data[a,b]"), equalTo("comma")); + assertThat(FieldPaths.resolveValues(root, "data[a,b],items[0].name"), equalTo("comma")); + } + + @Test + void shouldResolveRootContainersAndChainedIndices() { + assertThat(FieldPaths.resolveValue(new int[][] { { 10, 20 }, { 30, 40 } }, "[1][0]"), equalTo(30)); + assertThat(FieldPaths.resolveValue(List.of(List.of("value")), "[0][0]"), equalTo("value")); + assertThat(FieldPaths.resolveValue(Map.of("a.b", "value"), "['a.b']"), equalTo("value")); + assertThat(FieldPaths.resolveValue(Map.of("a,b", "value"), "a,b"), equalTo("value")); + } + + @Test + void shouldTrimOnlyCompleteAlternatives() { + WithContainers root = new WithContainers(); - assertThat(paths.size(), equalTo(3)); - assertThat(paths.get(0), equalTo("entries[0].name")); - assertThat(paths.get(1), equalTo("data['a,b']")); - assertThat(paths.get(2), equalTo("items[1].name")); + assertThat(FieldPaths.resolveValues(root, " entries[0].name "), equalTo("fromArray")); + assertThat(FieldPaths.resolveValues(root, " data['key'] "), equalTo("fromMap")); + assertThat(FieldPaths.resolveValue(root, " entries[0].name"), nullValue()); + assertThat(FieldPaths.resolveValue(root, "entries[0].name "), nullValue()); + assertThat(FieldPaths.resolveValues(root, "entries[0]. name,items[0].name"), equalTo("fromList")); } @Test diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java index 989e6830..47e125a6 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathTest.java @@ -15,6 +15,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.LinkedHashMap; @@ -22,6 +23,9 @@ import java.util.Map; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.morphix.lang.collections.FastArrayList; /** @@ -37,6 +41,8 @@ class FieldsSafeGetByPathTest { private static final String NON_EXISTENT_FIELD = "$NonExistentField$"; + private final Data data = new Data(); + public static class WithTransformingGetter { public String value = FIELD_VALUE; @@ -184,4 +190,149 @@ public static class Wrapper { public WithIndexedContainers row; } + + private record Person(String name) { + // empty + } + + @SuppressWarnings("unused") + private static final class Data { + + private final Person person = new Person("Alice"); + + private final List persons = List.of( + new Person("Alice"), + new Person("Bob")); + + private final String[] array = { "Alice", "Bob" }; + + private final int[] numbers = { 10, 20, 30 }; + + private final int[][] matrix = { + { 10, 20 }, + { 30, 40 } + }; + + private final Map attributes = Map.of( + "name", "Alice", + "first.name", "Bob", + "a,b", "comma", + "a]b", "bracket", + "a'b", "quote", + "a\\b", "backslash", + "0", "zero", + "", "empty", + "size", "map size"); + + private final Object missing = null; + } + + @ParameterizedTest + @CsvSource({ + "person.name, Alice", + "persons[0].name, Alice", + "persons[1].name, Bob", + "array[0], Alice", + "array[1], Bob", + "attributes.name, Alice", + "attributes[name], Alice", + "attributes['name'], Alice", + "attributes[\"name\"], Alice", + "attributes['first.name'], Bob", + "attributes['0'], zero", + "attributes[''], empty", + "attributes.size, map size", + "attributes['a]b'], bracket" + }) + void shouldResolvePath(final String path, final String expected) { + var result = Fields.Safe.getByPath(data, path); + + assertThat(result, equalTo(expected)); + } + + @Test + void shouldResolvePrimitiveArrayElement() { + Integer result = Fields.Safe.getByPath(data, "numbers[1]"); + + assertThat(result, equalTo(20)); + } + + @Test + void shouldResolveNestedArrayElement() { + Integer result = Fields.Safe.getByPath(data, "matrix[1][0]"); + + assertThat(result, equalTo(30)); + } + + @Test + void shouldResolveKeyContainingComma() { + var result = Fields.Safe.getByPath(data, "attributes['a,b']"); + + assertThat(result, equalTo("comma")); + } + + @Test + void shouldResolveKeyContainingQuote() { + var result = Fields.Safe.getByPath(data, "attributes['a\\'b']"); + + assertThat(result, equalTo("quote")); + } + + @Test + void shouldResolveKeyContainingBackslash() { + var result = Fields.Safe.getByPath(data, "attributes['a\\\\b']"); + + assertThat(result, equalTo("backslash")); + } + + @Test + void shouldResolveRootList() { + List persons = List.of(new Person("Alice")); + + var result = Fields.Safe.getByPath(persons, "[0].name"); + + assertThat(result, equalTo("Alice")); + } + + @Test + void shouldResolveRootMap() { + Map map = Map.of("name", "Alice"); + + var result = Fields.Safe.getByPath(map, "['name']"); + + assertThat(result, equalTo("Alice")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + ".", + ".person", + "person.", + "person..name", + "person.[0]", + "persons[]", + "persons[", + "persons[0", + "persons[0]]", + "persons[-1]", + "persons[100]", + "persons[2147483648]", + "persons[0]name", + "persons[0].", + "attributes['name]", + "attributes['name'", + "attributes['name']name", + "attributes[unknown]", + "missing.name", + "missing[0]", + "person.unknown", + "unknown" + }) + void shouldReturnNullForInvalidOrUnresolvedPath(final String path) { + var result = Fields.Safe.getByPath(data, path); + + assertNull(result); + } } diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 2b4bde62..6c5cf271 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -164,4 +164,21 @@ void shouldNotSplitOnCommaInsideBrackets() { assertThat(value, equalTo("commaKey")); } + @Test + void shouldResolveFallbackAfterMalformedAlternative() { + B b = new B(); + b.a = new A(); + b.a.x = TEST_STRING; + + assertThat(Fields.Safe.getByPaths(b, ".bad,keyed[],a.x"), equalTo(TEST_STRING)); + } + + @Test + void shouldResolveFallbackAfterEscapedBackslash() { + B b = new B(); + b.a = new A(); + b.a.x = TEST_STRING; + + assertThat(Fields.Safe.getByPaths(b, "keyed['missing\\\\'].x,a.x"), equalTo(TEST_STRING)); + } }