C0urante commented on code in PR #12637:
URL: https://github.com/apache/kafka/pull/12637#discussion_r1149375240


##########
connect/transforms/src/main/java/org/apache/kafka/connect/transforms/field/SingleFieldPath.java:
##########
@@ -0,0 +1,585 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.kafka.connect.transforms.field;
+
+import org.apache.kafka.common.cache.Cache;
+import org.apache.kafka.common.cache.LRUCache;
+import org.apache.kafka.common.cache.SynchronizedCache;
+import org.apache.kafka.connect.data.Field;
+import org.apache.kafka.connect.data.Schema;
+import org.apache.kafka.connect.data.Schema.Type;
+import org.apache.kafka.connect.data.SchemaBuilder;
+import org.apache.kafka.connect.data.Struct;
+import org.apache.kafka.connect.transforms.util.SchemaUtil;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A FieldPath is composed by one or many field names, known as steps,
+ * to access values within a data object (either {@code Struct} or {@code 
Map<String, Object>}).a
+ * <p>
+ * If the SMT requires accessing multiple fields on the same data object,
+ * use {@code FieldPaths} instead.
+ * <p>
+ * The field path semantics are defined by the syntax version {@code 
FieldSyntaxVersion}.
+ * <p>
+ * Paths are calculated once and cached for further access.
+ * <p>
+ * Invariants:
+ * <li>
+ *     <ul>A field path can contain one or more steps</ul>
+ * </li>
+ *
+ * See KIP-821.
+ *
+ * @see FieldSyntaxVersion
+ * @see MultiFieldPaths
+ */
+public class SingleFieldPath implements FieldPath {
+
+    private static final char BACKTICK_CHAR = '`';
+    private static final char DOT_CHAR = '.';
+    private static final char BACKSLASH_CHAR = '\\';
+
+    private static final Cache<String, SingleFieldPath> PATHS_CACHE = new 
SynchronizedCache<>(new LRUCache<>(16));
+
+    private final String[] path;
+
+    static SingleFieldPath ofV1(String field) {
+        return of(field, FieldSyntaxVersion.V1);
+    }
+
+    static SingleFieldPath ofV2(String field) {
+        return of(field, FieldSyntaxVersion.V2);
+    }
+
+    /**
+     * If version is V2, then paths are cached for further access.
+     *
+     * @param field   field path expression
+     * @param version field syntax version
+     */
+    public static SingleFieldPath of(String field, FieldSyntaxVersion version) 
{
+        if ((field == null || field.isEmpty()) // empty path
+                || version.equals(FieldSyntaxVersion.V1)) { // or V1
+            return new SingleFieldPath(field, version);
+        } else { // use cache when V2
+            final SingleFieldPath found = PATHS_CACHE.get(field);
+            if (found != null) {
+                return found;
+            } else {
+                final SingleFieldPath fieldPath = new SingleFieldPath(field, 
version);
+                PATHS_CACHE.put(field, fieldPath);
+                return fieldPath;
+            }
+        }
+    }
+
+    SingleFieldPath(String pathText, FieldSyntaxVersion version) {
+        if (pathText == null || pathText.isEmpty()) { // empty path
+            this.path = new String[] {};
+        } else {
+            switch (version) {
+                case V1: // backward compatibility
+                    this.path = new String[] {pathText};
+                    break;
+                case V2:
+                    path = buildFieldPathV2(pathText);
+                    break;
+                default:
+                    throw new IllegalArgumentException("Unknown syntax 
version: " + version);
+            }
+        }
+    }
+
+    private String[] buildFieldPathV2(String pathText) {
+        // if no dots or wrapping backticks are used, then return path with 
single step
+        if (!pathText.contains(String.valueOf(DOT_CHAR))) {
+            return new String[] {pathText};
+        } else {
+            // prepare for tracking path steps
+            final List<String> steps = new ArrayList<>();
+            // avoid creating new string on changes
+            final StringBuilder s = new StringBuilder(pathText);
+
+            while (s.length() > 0) { // until path is traversed
+                // start processing backtick pair, if any
+                if (s.charAt(0) == BACKTICK_CHAR) {
+                    s.deleteCharAt(0);
+
+                    // find backtick closing pair
+                    int idx = 0;
+                    while (idx >= 0) {
+                        idx = s.indexOf(String.valueOf(BACKTICK_CHAR), idx);
+                        if (idx == -1) { // if not found, fail
+                            throw new IllegalArgumentException("Incomplete 
backtick pair at [...]`" + s);
+                        }
+                        // check that it is not escaped or wrapped in another 
backticks pair
+                        if (idx < s.length() - 1 // not wrapping the whole 
field path
+                                && (s.charAt(idx + 1) != DOT_CHAR // not 
wrapping
+                                || s.charAt(idx - 1) == BACKSLASH_CHAR)) { // 
... or escaped
+                            idx++; // move index forward and keep searching
+                        } else { // it's the closing pair
+                            steps.add(escapeBackticks(s.substring(0, idx)));
+                            s.delete(0, idx + 2); // rm backtick and dot
+                            break;
+                        }
+                    }
+                } else { // process dots in path
+                    final int atDot = s.indexOf(String.valueOf(DOT_CHAR));
+                    if (atDot > 0) { // get path step and move forward
+                        steps.add(escapeBackticks(s.substring(0, atDot)));
+                        s.delete(0, atDot + 1);
+                    } else { // add all
+                        steps.add(escapeBackticks(s.toString()));
+                        s.delete(0, s.length());
+                    }
+                }
+            }
+
+            return steps.toArray(new String[0]);
+        }
+    }
+
+    /**
+     * Return field name with escaped backticks, if any.
+     *
+     * @param field potentially containing backticks
+     * @throws IllegalArgumentException when there are incomplete backtick 
pairs
+     */
+    private String escapeBackticks(String field) {
+        final StringBuilder s = new StringBuilder(field);
+        int idx = 0;
+        while (idx >= 0) {
+            idx = s.indexOf(String.valueOf(BACKTICK_CHAR), idx + 1);
+            if (idx >= 1 && s.length() > 2) {
+                if (s.charAt(idx - 1) == DOT_CHAR
+                        || (idx < s.length() - 1 && s.charAt(idx + 1) == 
DOT_CHAR
+                        && s.charAt(idx - 1) != BACKSLASH_CHAR)) {
+                    throw new IllegalArgumentException("Incomplete backtick 
pair at [...]" + field);
+                }
+                if (s.charAt(idx - 1) == BACKSLASH_CHAR) { // escape backtick
+                    if ((idx == 1 && s.charAt(0) == BACKSLASH_CHAR) // at the 
beginning: \`foo[...]
+                            || idx == s.length() - 1) { // at the end: 
[...]baz\`
+                        s.deleteCharAt(idx - 1);
+                    } else if ((idx > 2 && s.charAt(idx - 2) == DOT_CHAR) // 
after a dot: [...].\`bar[...]
+                            || (idx < s.length() - 1 && s.charAt(idx + 1) == 
DOT_CHAR)) { // before a dot: [...]bar\`.[...]
+                        s.deleteCharAt(idx - 1);
+                    }
+                }
+            }
+        }
+        return s.toString();
+    }

Review Comment:
   I took a stab at simplifying this whole method to 1) remove unnecessary 
`StringBuilder` instantiation, 2) handle all backtick escape logic on the fly 
(instead of in a follow-up step with the `escapeBackticks` method), and 3) 
follow the slightly-tweaked spec I outlined in my latest comment. LMKWYT
   
   ```suggestion
       private String[] buildFieldPathV2(String pathText) {
           final List<String> steps = new ArrayList<>();
           int idx = 0;
           while (idx < pathText.length() && idx >= 0) {
               if (pathText.charAt(idx) != BACKTICK_CHAR) {
                   final int start = idx;
                   idx = pathText.indexOf(String.valueOf(DOT_CHAR), idx);
                   if (idx > 0) { // get path step and move forward
                       String field = pathText.substring(start, idx);
                       steps.add(field);
                       idx++;
                   } else { // add all
                       String field = pathText.substring(start);
                       steps.add(field);
                   }
               } else {
                   StringBuilder field = new StringBuilder();
                   idx++;
                   int start = idx;
                   while (true) {
                       idx = pathText.indexOf(String.valueOf(BACKTICK_CHAR), 
idx);
                       if (idx == -1) { // if not found, fail
                           throw new IllegalArgumentException("Incomplete 
backtick pair in path: " + pathText);
                       }
                       boolean endOfPath = idx >= pathText.length() - 1;
                       if (endOfPath) {
                           field.append(pathText, start, idx);
                           // we've reached the end of the path, and the last 
character is the backtick
                           steps.add(field.toString());
                           idx++;
                           break;
                       }
                       if (pathText.charAt(idx + 1) != DOT_CHAR) {
                           // this backtick isn't followed by a dot; include it 
in the field name, but continue
                           // looking for a matching backtick that is followed 
by a dot
                           idx++;
                           continue;
                       }
                       if (pathText.charAt(idx - 1) == BACKSLASH_CHAR) {
                           // this backtick was escaped; include it in the 
field name, but continue
                           // looking for an unescaped matching backtick
                           field.append(pathText, start, idx - 1)
                                   .append(BACKTICK_CHAR);
                           idx++;
                           start = idx;
                           continue;
                       }
                       // we've found our matching backtick
                       field.append(pathText, start, idx);
                       steps.add(field.toString());
                       idx += 2; // increment by two to include the backtick 
and the dot after it
                       break;
                   }
               }
           }
           return steps.toArray(new String[0]);
       }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscr...@kafka.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to