You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "ocean-zhc (via GitHub)" <gi...@apache.org> on 2025/04/02 03:26:46 UTC

[PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

ocean-zhc opened a new pull request, #9103:
URL: https://github.com/apache/seatunnel/pull/9103

   …is inconsistent with the import failure
   
   <!--
   
   Thank you for contributing to SeaTunnel! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   ## Contribution Checklist
     - Make sure that the pull request corresponds to a [GITHUB issue](https://github.com/apache/seatunnel/issues).
     - Name the pull request in the form "[Feature] [component] Title of the pull request", where *Feature* can be replaced by `Hotfix`, `Bug`, etc.
     - Minor fixes should be named following this pattern: `[hotfix] [docs] Fix typo in README.md doc`.
   -->
   
   ### Purpose of this pull request
   
   <!-- Describe the purpose of this pull request. For example: This pull request adds checkstyle plugin.-->
   
   
   ### Does this PR introduce _any_ user-facing change?
   
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released SeaTunnel versions or within the unreleased branches such as dev.
   If no, write 'No'.
   If you are adding/modifying connector documents, please follow our new specifications: https://github.com/apache/seatunnel/issues/4544.
   -->
   
   
   ### How was this patch tested?
   
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If you are adding E2E test cases, maybe refer to https://github.com/apache/seatunnel/blob/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/mysqlcdc_to_mysql.conf, here is a good example.
   -->
   
   
   ### Check list
   
   * [ ] If any new Jar binary package adding in your PR, please add License Notice according
     [New License Guide](https://github.com/apache/seatunnel/blob/dev/docs/en/contribution/new-license.md)
   * [ ] If necessary, please update the documentation to describe the new feature. https://github.com/apache/seatunnel/tree/dev/docs
   * [ ] If you are contributing the connector code, please check that the following files are updated:
     1. Update [plugin-mapping.properties](https://github.com/apache/seatunnel/blob/dev/plugin-mapping.properties) and add new connector information in it
     2. Update the pom file of [seatunnel-dist](https://github.com/apache/seatunnel/blob/dev/seatunnel-dist/pom.xml)
     3. Add ci label in [label-scope-conf](https://github.com/apache/seatunnel/blob/dev/.github/workflows/labeler/label-scope-conf.yml)
     4. Add e2e testcase in [seatunnel-e2e](https://github.com/apache/seatunnel/tree/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/)
     5. Update connector [plugin_config](https://github.com/apache/seatunnel/blob/dev/config/plugin_config)
   * [ ] Update the [`release-note`](https://github.com/apache/seatunnel/blob/dev/release-note.md).


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2084564497


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/AbstractJsonPathProcessor.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Abstract implementation of JsonPathProcessor providing common functionality. */
+public abstract class AbstractJsonPathProcessor implements JsonPathProcessor {
+
+    /** Flag to indicate whether to return null for missing fields */
+    private boolean jsonFiledMissedReturnNull = false;
+
+    /**
+     * Set whether to return null for missing fields.
+     *
+     * @param jsonFiledMissedReturnNull true to return null for missing fields, false otherwise
+     */
+    public void setJsonFiledMissedReturnNull(boolean jsonFiledMissedReturnNull) {
+        this.jsonFiledMissedReturnNull = jsonFiledMissedReturnNull;
+    }
+
+    /**
+     * Check if json fields with missing values should return null. This is used to determine
+     * whether to validate result consistency.
+     *
+     * @return true if missing fields should return null, false otherwise
+     */
+    protected boolean isJsonFiledMissedReturnNull() {
+        return jsonFiledMissedReturnNull;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String extractCommonParentPath(JsonPath[] paths);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String getRelativePath(String parentPath, String fullPath);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract boolean canProcess(String pathString);
+
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {
+        // Default implementation - can be overridden by subclasses
+        List<List<String>> results = new ArrayList<>(paths.length);
+
+        // Read all paths
+        for (JsonPath path : paths) {
+            results.add(jsonReadContext.read(path));
+        }
+
+        // Only validate consistency if jsonFiledMissedReturnNull is false
+        boolean shouldValidate = !isJsonFiledMissedReturnNull();
+        if (shouldValidate) {
+            validateResultsConsistency(results, paths);
+        }
+
+        return dataFlip(results);
+    }
+
+    /**
+     * Helper method to validate that all results have the same size.
+     *
+     * @param results The list of results to validate
+     * @param paths The JsonPath objects used to generate the results
+     * @throws HttpConnectorException if results are inconsistent
+     */
+    protected void validateResultsConsistency(List<List<String>> results, JsonPath[] paths) {
+        if (results.isEmpty()) {
+            return;
+        }
+
+        int expectedSize = results.get(0).size();
+        for (int i = 1; i < results.size(); i++) {
+            if (results.get(i).size() != expectedSize) {
+                throw new HttpConnectorException(
+                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                        String.format(
+                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
+                                paths[0].getPath(),
+                                expectedSize,
+                                paths[i].getPath(),
+                                results.get(i).size()));
+            }
+        }
+    }
+
+    /**
+     * Flips a matrix of results so that rows become columns and vice versa.
+     *
+     * @param results The original data matrix
+     * @return The flipped data matrix
+     */
+    protected List<List<String>> dataFlip(List<List<String>> results) {
+        List<List<String>> datas = new ArrayList<>();
+
+        for (int i = 0; i < results.size(); i++) {
+            List<String> result = results.get(i);
+            if (i == 0) {
+                for (Object o : result) {
+                    String val = o == null ? null : o.toString();
+                    List<String> row = new ArrayList<>(results.size());
+                    row.add(val);
+                    datas.add(row);
+                }
+            } else {
+                for (int j = 0; j < result.size(); j++) {
+                    Object o = result.get(j);
+                    String val = o == null ? null : o.toString();
+                    List<String> row = datas.get(j);
+                    row.add(val);
+                }
+            }
+        }
+
+        return datas;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractValue(ReadContext objContext, String relativePath) {
+        try {
+            Object value = objContext.read(relativePath);
+            if (value == null) {
+                return null;
+            }
+            if (value instanceof List) {
+                List<?> list = (List<?>) value;
+                return !list.isEmpty() ? list.toString() : null;

Review Comment:
   We should return json style list string. Not use list toString value.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2084553158


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/ObjectJsonPathProcessor.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/** Processor for handling JsonPath with dot notation (standard object notation). */
+public class ObjectJsonPathProcessor extends AbstractJsonPathProcessor {
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean canProcess(String pathString) {
+        // Check if path uses dot notation and doesn't use array notation or bracket notation
+        return pathString.contains(".")
+                && !pathString.contains("[*]")
+                && !pathString.contains("['")
+                && !pathString.contains("[\"");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractCommonParentPath(JsonPath[] paths) {

Review Comment:
   But it only used in `ArrayJsonPathProcessor`.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2044199060


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -257,27 +257,139 @@ private List<Map<String, String>> parseToMap(List<List<String>> datas, JsonField
 
     private List<List<String>> decodeJSON(String data) {
         ReadContext jsonReadContext = JsonPath.using(jsonConfiguration).parse(data);
-        List<List<String>> results = new ArrayList<>(jsonPaths.length);
-        for (JsonPath path : jsonPaths) {
-            List<String> result = jsonReadContext.read(path);
-            results.add(result);
+
+        if (httpParameter.isJsonFiledMissedReturnNull()) {
+            // Extract the common parent path from all configured paths
+            String commonParentPath = extractCommonParentPath(jsonPaths);
+            if (commonParentPath == null) {
+                throw new HttpConnectorException(
+                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                        "Could not find common parent path in JsonPaths. All paths must share a common array parent.");
+            }
+
+            // Get all objects under the common parent path
+            List<Map<String, Object>> objects;
+            try {
+                objects = jsonReadContext.read(commonParentPath);
+            } catch (Exception e) {

Review Comment:
   > The current implementation is a bit complicated. In fact, the jsonpath can do this by itself. In jsonpath,
   > 
   > https://github.com/apache/seatunnel/blob/d2ac555db1772cf58342db7709015a3b594aa87e/seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java#L64
   > 
   > we already enabled `DEFAULT_PATH_LEAF_TO_NULL`,
   > ![image](https://private-user-images.githubusercontent.com/32387433/433642765-a9a187db-289b-46b5-aba4-0d133c48f01a.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDQ3MTIzNDQsIm5iZiI6MTc0NDcxMjA0NCwicGF0aCI6Ii8zMjM4NzQzMy80MzM2NDI3NjUtYTlhMTg3ZGItMjg5Yi00NmI1LWFiYTQtMGQxMzNjNDhmMDFhLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNTA0MTUlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjUwNDE1VDEwMTQwNFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPWY3OWJlYjJmYTI2MmM1YmU1NzFhYzdiMGMzMWEwMzAyNDI3NmRkNjcwODNiNThiMzQwMzU1YmI3NmY4Yzc0N2MmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.K7ZnlKDtaw5dv5NI8zMBKHRI0oGFxA_0YMLbZrx5Fxo)
   > according the comment, when some path leaf not existed, it should return null. That's what we want, so we should check why this configure not work first.
   
   DEFAULT_PATH_LEAF_TO_NULL can't be handled for complex, this configuration is only effective for leaf nodes, and can't be handled for missing parent nodes, see details:
   
   <img width="1301" alt="image" src="https://github.com/user-attachments/assets/b88d93c1-aaa2-49de-bbb1-feeebae33cf5" />
   
   
   <img width="1655" alt="image" src="https://github.com/user-attachments/assets/73c85e6f-bd77-4f96-bbaf-5ef27d82268e" />
   
   
   Get parent node according to user configuration, e.g. 
   key1_1 = "$.result.rows[*].key1.key1_1" 
   key2_1 = "$.result.rows[*].key2.key2_1" 
   will get result.rows[*] as the parent node, and the child node is missing to fill null
   
   result:
   <img width="837" alt="image" src="https://github.com/user-attachments/assets/33254679-9b78-49ed-8efc-bb2dc9cde62c" />
   
   unit test:
   https://github.com/ocean-zhc/seatunnel/blob/dev/seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullComplexTest.java
   
   https://github.com/ocean-zhc/seatunnel/blob/dev/seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullTest.java
   
   
   
   



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2080965612


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/ObjectJsonPathProcessor.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/** Processor for handling JsonPath with dot notation (standard object notation). */
+public class ObjectJsonPathProcessor extends AbstractJsonPathProcessor {
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean canProcess(String pathString) {
+        // Check if path uses dot notation and doesn't use array notation or bracket notation
+        return pathString.contains(".")
+                && !pathString.contains("[*]")
+                && !pathString.contains("['")
+                && !pathString.contains("[\"");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractCommonParentPath(JsonPath[] paths) {

Review Comment:
   Used



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2107261486


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/BracketJsonPathProcessor.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Processor for handling JsonPath with bracket notation (e.g., $['result']['value']). */
+public class BracketJsonPathProcessor extends AbstractJsonPathProcessor {
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {

Review Comment:
   Recheck the logic of `BracketJsonPathProcessor` and `ObjectJsonPathProcessor`. They are totally same.



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -418,47 +421,24 @@ private void collect(Collector<SeaTunnelRow> output, String data) throws IOExcep
         deserializationCollector.collect(contentData.getBytes(), output);
     }
 
-    private List<Map<String, String>> parseToMap(List<List<String>> datas, JsonField jsonField) {
-        List<Map<String, String>> decodeDatas = new ArrayList<>(datas.size());
-        String[] keys = jsonField.getFields().keySet().toArray(new String[] {});
-
-        for (List<String> data : datas) {
-            Map<String, String> decodeData = new HashMap<>(jsonField.getFields().size());
-            final int[] index = {0};
-            data.forEach(
-                    field -> {
-                        decodeData.put(keys[index[0]], field);
-                        index[0]++;
-                    });
-            decodeDatas.add(decodeData);
-        }
-
-        return decodeDatas;
-    }
-
     private List<List<String>> decodeJSON(String data) {
         ReadContext jsonReadContext = JsonPath.using(jsonConfiguration).parse(data);
-        List<List<String>> results = new ArrayList<>(jsonPaths.length);
-        for (JsonPath path : jsonPaths) {
-            List<String> result = jsonReadContext.read(path);
-            results.add(result);
-        }
-        for (int i = 1; i < results.size(); i++) {
-            List<?> result0 = results.get(0);
-            List<?> result = results.get(i);
-            if (result0.size() != result.size()) {
-                throw new HttpConnectorException(
-                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
-                        String.format(
-                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
-                                jsonPaths[0].getPath(),
-                                result0.size(),
-                                jsonPaths[i].getPath(),
-                                result.size()));
-            }
+        boolean jsonFiledMissedReturnNull = httpParameter.isJsonFiledMissedReturnNull();
+        if (jsonFiledMissedReturnNull) {
+            // Get the appropriate processor for the JsonPaths, passing the
+            // jsonFiledMissedReturnNull flag
+            JsonPathProcessor processor =
+                    JsonPathProcessorFactory.getProcessor(this.jsonPaths, true);
+            return processor.processJsonData(jsonReadContext, this.jsonPaths);
+        } else {
+            // Standard processing for strict fields
+            return JsonPathProcessorFactory.getProcessor(this.jsonPaths)
+                    .processJsonData(jsonReadContext, this.jsonPaths);
         }

Review Comment:
   ```suggestion
           return JsonPathProcessorFactory.getProcessor(this.jsonPaths, httpParameter.isJsonFiledMissedReturnNull())
                   .processJsonData(jsonReadContext, this.jsonPaths);
   ```



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc closed pull request #9103: [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure
URL: https://github.com/apache/seatunnel/pull/9103


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2080878429


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathUtils.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Utility class for JsonPath operations. */
+public class JsonPathUtils {
+
+    private static final Option[] DEFAULT_OPTIONS = {
+        Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST, Option.DEFAULT_PATH_LEAF_TO_NULL
+    };
+
+    private static final Configuration JSON_CONFIGURATION =
+            Configuration.defaultConfiguration().addOptions(DEFAULT_OPTIONS);
+
+    /**
+     * Creates a ReadContext from a JSON string.
+     *
+     * @param json The JSON string
+     * @return A ReadContext for the JSON
+     */
+    public static ReadContext parseJson(String json) {
+        return JsonPath.using(JSON_CONFIGURATION).parse(json);
+    }
+
+    /**
+     * Extracts data from JSON using JsonPaths.
+     *
+     * @param json The JSON string to parse
+     * @param jsonField The JsonField containing path mappings
+     * @param allowNullFields Whether to allow missing fields
+     * @return List of data extracted from JSON
+     */
+    public static List<Map<String, String>> extractData(
+            String json, JsonField jsonField, boolean allowNullFields) {
+        // Parse JSON into ReadContext
+        ReadContext jsonReadContext = parseJson(json);
+
+        // Convert JsonField to JsonPath array
+        JsonPath[] jsonPaths = createJsonPaths(jsonField);
+
+        // Get appropriate processor with jsonFiledMissedReturnNull flag
+        JsonPathProcessor processor =
+                JsonPathProcessorFactory.getProcessor(jsonPaths, allowNullFields);
+
+        // Process JSON data based on the processor
+        List<List<String>> results = processor.processJsonData(jsonReadContext, jsonPaths);
+
+        // Convert results to maps
+        return parseToMap(results, jsonField);
+    }
+
+    /**
+     * Creates JsonPath array from JsonField.
+     *
+     * @param jsonField The JsonField to convert
+     * @return Array of JsonPath objects
+     */
+    public static JsonPath[] createJsonPaths(JsonField jsonField) {
+        if (jsonField == null || jsonField.getFields() == null || jsonField.getFields().isEmpty()) {
+            throw new HttpConnectorException(
+                    HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                    "JsonField cannot be null or empty");
+        }
+
+        JsonPath[] jsonPaths = new JsonPath[jsonField.getFields().size()];
+        int index = 0;
+        for (String pathString : jsonField.getFields().values()) {
+            jsonPaths[index++] = JsonPath.compile(pathString);
+        }
+
+        return jsonPaths;
+    }
+
+    /**
+     * Converts parsed data to a list of maps.
+     *
+     * @param data The raw data (list of lists)
+     * @param jsonField The JsonField containing field names
+     * @return List of maps with field names as keys
+     */
+    public static List<Map<String, String>> parseToMap(
+            List<List<String>> data, JsonField jsonField) {
+        List<Map<String, String>> resultList = new ArrayList<>(data.size());
+        String[] keys = jsonField.getFields().keySet().toArray(new String[0]);
+
+        for (List<String> row : data) {
+            Map<String, String> resultMap = new HashMap<>(jsonField.getFields().size());
+            for (int i = 0; i < row.size(); i++) {
+                resultMap.put(keys[i], row.get(i));
+            }
+            resultList.add(resultMap);
+        }
+
+        return resultList;
+    }
+
+    /**
+     * Extracts the common parent path from JsonPaths.
+     *
+     * @param paths Array of JsonPath objects
+     * @return The common parent path
+     */
+    public static String extractCommonParentPath(JsonPath[] paths) {
+        return JsonPathProcessorFactory.getProcessor(paths).extractCommonParentPath(paths);
+    }
+
+    /**
+     * Gets a relative path from a parent path and a full path.
+     *
+     * @param parentPath The parent path
+     * @param fullPath The full path
+     * @return The relative path
+     */
+    public static String getRelativePath(String parentPath, String fullPath) {
+        return JsonPathProcessorFactory.getProcessor(fullPath)
+                .getRelativePath(parentPath, fullPath);
+    }

Review Comment:
   Moved out



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -467,8 +447,8 @@ private String getPartOfJson(String data) {
     }
 
     private List<List<String>> dataFlip(List<List<String>> results) {

Review Comment:
   Moved out



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathUtils.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Utility class for JsonPath operations. */
+public class JsonPathUtils {
+
+    private static final Option[] DEFAULT_OPTIONS = {
+        Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST, Option.DEFAULT_PATH_LEAF_TO_NULL
+    };
+
+    private static final Configuration JSON_CONFIGURATION =
+            Configuration.defaultConfiguration().addOptions(DEFAULT_OPTIONS);
+
+    /**
+     * Creates a ReadContext from a JSON string.
+     *
+     * @param json The JSON string
+     * @return A ReadContext for the JSON
+     */
+    public static ReadContext parseJson(String json) {
+        return JsonPath.using(JSON_CONFIGURATION).parse(json);
+    }
+
+    /**
+     * Extracts data from JSON using JsonPaths.
+     *
+     * @param json The JSON string to parse
+     * @param jsonField The JsonField containing path mappings
+     * @param allowNullFields Whether to allow missing fields
+     * @return List of data extracted from JSON
+     */
+    public static List<Map<String, String>> extractData(

Review Comment:
   Moved out



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2084553158


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/ObjectJsonPathProcessor.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/** Processor for handling JsonPath with dot notation (standard object notation). */
+public class ObjectJsonPathProcessor extends AbstractJsonPathProcessor {
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean canProcess(String pathString) {
+        // Check if path uses dot notation and doesn't use array notation or bracket notation
+        return pathString.contains(".")
+                && !pathString.contains("[*]")
+                && !pathString.contains("['")
+                && !pathString.contains("[\"");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractCommonParentPath(JsonPath[] paths) {

Review Comment:
   But it only used in `ArrayJsonPathProcessor`. Same as `getRelativePath`, `readObjectsFromPath`.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2047213925


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullTest.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpClientProvider;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpResponse;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpParameter;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpRequestMethod;
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.source.HttpSourceReader;
+import org.apache.seatunnel.connectors.seatunnel.http.source.SimpleTextDeserializationSchema;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class JsonFieldMissedReturnNullTest {
+
+    private HttpParameter httpParameter;
+    private JsonField jsonField;
+    private SimpleTextDeserializationSchema deserializationSchema;
+
+    @Mock private SingleSplitReaderContext context;
+
+    @Mock private Collector<SeaTunnelRow> collector;
+
+    @Mock private HttpClientProvider httpClientProvider;
+
+    @Mock private HttpResponse httpResponse;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+
+        httpParameter = new HttpParameter();
+        httpParameter.setUrl("http://test-url.com");
+        httpParameter.setMethod(HttpRequestMethod.GET);
+
+        Map<String, String> fields = new HashMap<>();
+        fields.put("key1", "$[*].key1");
+        fields.put("key2", "$[*].key2");
+        jsonField = JsonField.builder().fields(fields).build();
+
+        // Create the schema with two string fields
+        SeaTunnelRowType rowType =
+                new SeaTunnelRowType(
+                        new String[] {"key1", "key2"},
+                        new SeaTunnelDataType[] {BasicType.STRING_TYPE, BasicType.STRING_TYPE});
+        deserializationSchema = new SimpleTextDeserializationSchema(rowType);
+
+        // Setup mocks
+        when(httpResponse.getCode()).thenReturn(200);
+        when(collector.getCheckpointLock()).thenReturn(new Object());
+    }
+
+    @Test
+    public void testJsonFieldMissedReturnNull() throws Exception {
+        // Test data with missing fields
+        String testJsonData =
+                "[{\"key1\":\"value11\",\"key2\":\"value22\"},{\"key2\":\"value33\"},{\"key1\":\"value55\"}]";
+
+        // Set json_filed_missed_return_null to true
+        httpParameter.setJsonFiledMissedReturnNull(true);
+
+        // Setup HTTP response
+        when(httpResponse.getContent()).thenReturn(testJsonData);
+        when(httpClientProvider.execute(
+                        anyString(), anyString(), any(), any(), any(), any(Boolean.class)))
+                .thenReturn(httpResponse);
+
+        // Create HttpSourceReader
+        HttpSourceReader sourceReader =
+                new HttpSourceReader(
+                        httpParameter, context, deserializationSchema, jsonField, null);
+
+        // Use reflection to inject our mocked HTTP client
+        sourceReader.open(); // This creates the real HTTP client
+        Field httpClientField = HttpSourceReader.class.getDeclaredField("httpClient");
+        httpClientField.setAccessible(true);
+        httpClientField.set(sourceReader, httpClientProvider);
+
+        // Capture the rows collected
+        ArgumentCaptor<SeaTunnelRow> rowCaptor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+
+        // Call the method that processes data
+        sourceReader.pollNext(collector);
+
+        // Verify collector.collect was called 3 times (once for each JSON object)
+        verify(collector, times(1)).collect(rowCaptor.capture());

Review Comment:
   single call



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2297427580


##########
docs/en/connector-v2/source/Http.md:
##########
@@ -44,37 +44,38 @@ They can be downloaded via install-plugin.sh or from the Maven central repositor
 
 ## Source Options

Review Comment:
   please update zh docs too.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2125441334


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -418,47 +421,24 @@ private void collect(Collector<SeaTunnelRow> output, String data) throws IOExcep
         deserializationCollector.collect(contentData.getBytes(), output);
     }
 
-    private List<Map<String, String>> parseToMap(List<List<String>> datas, JsonField jsonField) {
-        List<Map<String, String>> decodeDatas = new ArrayList<>(datas.size());
-        String[] keys = jsonField.getFields().keySet().toArray(new String[] {});
-
-        for (List<String> data : datas) {
-            Map<String, String> decodeData = new HashMap<>(jsonField.getFields().size());
-            final int[] index = {0};
-            data.forEach(
-                    field -> {
-                        decodeData.put(keys[index[0]], field);
-                        index[0]++;
-                    });
-            decodeDatas.add(decodeData);
-        }
-
-        return decodeDatas;
-    }
-
     private List<List<String>> decodeJSON(String data) {
         ReadContext jsonReadContext = JsonPath.using(jsonConfiguration).parse(data);
-        List<List<String>> results = new ArrayList<>(jsonPaths.length);
-        for (JsonPath path : jsonPaths) {
-            List<String> result = jsonReadContext.read(path);
-            results.add(result);
-        }
-        for (int i = 1; i < results.size(); i++) {
-            List<?> result0 = results.get(0);
-            List<?> result = results.get(i);
-            if (result0.size() != result.size()) {
-                throw new HttpConnectorException(
-                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
-                        String.format(
-                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
-                                jsonPaths[0].getPath(),
-                                result0.size(),
-                                jsonPaths[i].getPath(),
-                                result.size()));
-            }
+        boolean jsonFiledMissedReturnNull = httpParameter.isJsonFiledMissedReturnNull();
+        if (jsonFiledMissedReturnNull) {
+            // Get the appropriate processor for the JsonPaths, passing the
+            // jsonFiledMissedReturnNull flag
+            JsonPathProcessor processor =
+                    JsonPathProcessorFactory.getProcessor(this.jsonPaths, true);
+            return processor.processJsonData(jsonReadContext, this.jsonPaths);
+        } else {
+            // Standard processing for strict fields
+            return JsonPathProcessorFactory.getProcessor(this.jsonPaths)
+                    .processJsonData(jsonReadContext, this.jsonPaths);
         }

Review Comment:
   @ocean-zhc 



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2074862797


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathProcessorFactory.java:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Factory for creating appropriate JsonPathProcessor instances based on the JsonPath format. */
+public class JsonPathProcessorFactory {
+
+    // List of all available processors
+    private static final List<JsonPathProcessor> PROCESSORS = new ArrayList<>();
+
+    static {
+        // Register all available processors in order of precedence
+        PROCESSORS.add(new ArrayJsonPathProcessor());
+        PROCESSORS.add(new BracketJsonPathProcessor());
+        PROCESSORS.add(new ObjectJsonPathProcessor());
+    }

Review Comment:
   If a jsonpath contains three features of `$.store['book'][*].title`, can it still be processed normally? Please add corresponding test cases



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#issuecomment-2771249813

    #9093


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2080878809


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullTest.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpClientProvider;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpResponse;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpParameter;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpRequestMethod;
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.source.HttpSourceReader;
+import org.apache.seatunnel.connectors.seatunnel.http.source.SimpleTextDeserializationSchema;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class JsonFieldMissedReturnNullTest {
+
+    private HttpParameter httpParameter;
+    private JsonField jsonField;
+    private SimpleTextDeserializationSchema deserializationSchema;
+
+    @Mock private SingleSplitReaderContext context;
+
+    @Mock private Collector<SeaTunnelRow> collector;
+
+    @Mock private HttpClientProvider httpClientProvider;
+
+    @Mock private HttpResponse httpResponse;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+
+        httpParameter = new HttpParameter();
+        httpParameter.setUrl("http://test-url.com");
+        httpParameter.setMethod(HttpRequestMethod.GET);
+
+        Map<String, String> fields = new HashMap<>();
+        fields.put("key1", "$.result.key1");
+        fields.put("key2", "$.result2.key2.key2");
+        jsonField = JsonField.builder().fields(fields).build();
+
+        // Create the schema with two string fields
+        SeaTunnelRowType rowType =
+                new SeaTunnelRowType(
+                        new String[] {"key1", "key2"},
+                        new SeaTunnelDataType[] {BasicType.STRING_TYPE, BasicType.STRING_TYPE});
+        deserializationSchema = new SimpleTextDeserializationSchema(rowType);
+
+        // Setup mocks
+        when(httpResponse.getCode()).thenReturn(200);
+        when(collector.getCheckpointLock()).thenReturn(new Object());
+    }
+
+    @Test
+    public void testJsonFieldMissedReturnNull() throws Exception {
+        // Test data with missing fields  Non-array, no common parent path
+        String testJsonData =
+                "{\n"
+                        + "  \"result\": {\n"
+                        + "    \"key1\": \"value1\"\n"
+                        + "  },\n"
+                        + "  \"result2\": {}\n"
+                        + "}";
+
+        // Set json_filed_missed_return_null to true
+        httpParameter.setJsonFiledMissedReturnNull(true);
+
+        // Setup HTTP response
+        when(httpResponse.getContent()).thenReturn(testJsonData);
+        when(httpClientProvider.execute(
+                        anyString(), anyString(), any(), any(), any(), any(Boolean.class)))
+                .thenReturn(httpResponse);
+
+        // Create HttpSourceReader
+        HttpSourceReader sourceReader =
+                new HttpSourceReader(
+                        httpParameter, context, deserializationSchema, jsonField, null);
+
+        // Use reflection to inject our mocked HTTP client
+        sourceReader.open(); // This creates the real HTTP client
+        Field httpClientField = HttpSourceReader.class.getDeclaredField("httpClient");
+        httpClientField.setAccessible(true);
+        httpClientField.set(sourceReader, httpClientProvider);

Review Comment:
   Eliminates the use of reflection



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2039290111


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -262,21 +262,41 @@ private List<List<String>> decodeJSON(String data) {
             List<String> result = jsonReadContext.read(path);
             results.add(result);
         }
-        for (int i = 1; i < results.size(); i++) {
-            List<?> result0 = results.get(0);
-            List<?> result = results.get(i);
-            if (result0.size() != result.size()) {
-                throw new HttpConnectorException(
-                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
-                        String.format(
-                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
-                                jsonPaths[0].getPath(),
-                                result0.size(),
-                                jsonPaths[i].getPath(),
-                                result.size()));
+        if (httpParameter.isJsonFiledMissedReturnNull()) {
+            int maxLength = 0;
+            for (List<?> result : results) {
+                maxLength = Math.max(maxLength, result.size());
+            }
+            for (int i = 0; i < results.size(); i++) {
+                List<String> result = results.get(i);
+                if (result.size() < maxLength) {
+                    log.warn(
+                            "Field [{}] with size ({}) is less than max size ({}), will be padded with null values. "
+                                    + "This may happen when JSON paths return different numbers of elements.",
+                            jsonPaths[i].getPath(),
+                            result.size(),
+                            maxLength);
+                    for (int j = result.size(); j < maxLength; j++) {
+                        result.add(null);
+                    }
+                }
+            }
+        } else {

Review Comment:
   This solution will cause the data to be out of order. For example:
   ```json
   [{
   "key1":"value11",
   "key2":"value22"
   },
   {
   "key2":"value33"
   "key3":"value44"
   },
   {
   "key1":"value55"
   "key3":"value66"
   }
   ]
   ```
   Json Fields:
   
   ```hocon
   json_field = {
         key1 = "$[*].key1"
         key2 = "$[*].key2"
   }
   ```
   The expected results should be:
   | key1| key2|
   | --- | --- |
   | value11 | value22 |
   | null | value33 |
   | value55 | null |
   
   But current logic of results is:
   | key1| key2|
   | --- | --- |
   | value11 | value22 |
   | value55 | value33 |
   
   The current implementation just wants to add null at the end, but does not accurately locate which data is null.
   



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2039290111


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -262,21 +262,41 @@ private List<List<String>> decodeJSON(String data) {
             List<String> result = jsonReadContext.read(path);
             results.add(result);
         }
-        for (int i = 1; i < results.size(); i++) {
-            List<?> result0 = results.get(0);
-            List<?> result = results.get(i);
-            if (result0.size() != result.size()) {
-                throw new HttpConnectorException(
-                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
-                        String.format(
-                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
-                                jsonPaths[0].getPath(),
-                                result0.size(),
-                                jsonPaths[i].getPath(),
-                                result.size()));
+        if (httpParameter.isJsonFiledMissedReturnNull()) {
+            int maxLength = 0;
+            for (List<?> result : results) {
+                maxLength = Math.max(maxLength, result.size());
+            }
+            for (int i = 0; i < results.size(); i++) {
+                List<String> result = results.get(i);
+                if (result.size() < maxLength) {
+                    log.warn(
+                            "Field [{}] with size ({}) is less than max size ({}), will be padded with null values. "
+                                    + "This may happen when JSON paths return different numbers of elements.",
+                            jsonPaths[i].getPath(),
+                            result.size(),
+                            maxLength);
+                    for (int j = result.size(); j < maxLength; j++) {
+                        result.add(null);
+                    }
+                }
+            }
+        } else {

Review Comment:
   This solution will cause the data to be out of order. For example:
   ```json
   [{
   "key1":"value11",
   "key2":"value22"
   },
   {
   "key2":"value33"
   "key3":"value44"
   },
   {
   "key1":"value55"
   "key3":"value66"
   }
   ]
   ```
   Json Fields:
   
   ```hocon
   json_field = {
         key1 = "$[*].key1"
         key2 = "$[*].key2"
   }
   ```
   The expected results should be:
   | key1| key2|
   | --- | --- |
   | value11 | value22 |
   | null | value33 |
   | value55 | null |
   
   Before current logic of results is:
   | key1| key2|
   | --- | --- |
   | value11 | value22 |
   | value55 | value33 |
   
   The current implementation just wants to add null at the end, but does not accurately locate which data is null.
   



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2046200968


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullTest.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpClientProvider;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpResponse;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpParameter;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpRequestMethod;
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.source.HttpSourceReader;
+import org.apache.seatunnel.connectors.seatunnel.http.source.SimpleTextDeserializationSchema;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class JsonFieldMissedReturnNullTest {
+
+    private HttpParameter httpParameter;
+    private JsonField jsonField;
+    private SimpleTextDeserializationSchema deserializationSchema;
+
+    @Mock private SingleSplitReaderContext context;
+
+    @Mock private Collector<SeaTunnelRow> collector;
+
+    @Mock private HttpClientProvider httpClientProvider;
+
+    @Mock private HttpResponse httpResponse;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+
+        httpParameter = new HttpParameter();
+        httpParameter.setUrl("http://test-url.com");
+        httpParameter.setMethod(HttpRequestMethod.GET);
+
+        Map<String, String> fields = new HashMap<>();
+        fields.put("key1", "$[*].key1");
+        fields.put("key2", "$[*].key2");
+        jsonField = JsonField.builder().fields(fields).build();
+
+        // Create the schema with two string fields
+        SeaTunnelRowType rowType =
+                new SeaTunnelRowType(
+                        new String[] {"key1", "key2"},
+                        new SeaTunnelDataType[] {BasicType.STRING_TYPE, BasicType.STRING_TYPE});
+        deserializationSchema = new SimpleTextDeserializationSchema(rowType);
+
+        // Setup mocks
+        when(httpResponse.getCode()).thenReturn(200);
+        when(collector.getCheckpointLock()).thenReturn(new Object());
+    }
+
+    @Test
+    public void testJsonFieldMissedReturnNull() throws Exception {
+        // Test data with missing fields
+        String testJsonData =
+                "[{\"key1\":\"value11\",\"key2\":\"value22\"},{\"key2\":\"value33\"},{\"key1\":\"value55\"}]";
+
+        // Set json_filed_missed_return_null to true
+        httpParameter.setJsonFiledMissedReturnNull(true);
+
+        // Setup HTTP response
+        when(httpResponse.getContent()).thenReturn(testJsonData);
+        when(httpClientProvider.execute(
+                        anyString(), anyString(), any(), any(), any(), any(Boolean.class)))
+                .thenReturn(httpResponse);
+
+        // Create HttpSourceReader
+        HttpSourceReader sourceReader =
+                new HttpSourceReader(
+                        httpParameter, context, deserializationSchema, jsonField, null);
+
+        // Use reflection to inject our mocked HTTP client
+        sourceReader.open(); // This creates the real HTTP client
+        Field httpClientField = HttpSourceReader.class.getDeclaredField("httpClient");
+        httpClientField.setAccessible(true);
+        httpClientField.set(sourceReader, httpClientProvider);
+
+        // Capture the rows collected
+        ArgumentCaptor<SeaTunnelRow> rowCaptor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+
+        // Call the method that processes data
+        sourceReader.pollNext(collector);
+
+        // Verify collector.collect was called 3 times (once for each JSON object)
+        verify(collector, times(1)).collect(rowCaptor.capture());

Review Comment:
   The comment above this verification states that collector.collect should be called 3 times (once for each JSON object) while the code verifies a single call. Please clarify whether the collector should be invoked once or multiple times and adjust the comment or verification accordingly.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "LeonYoah (via GitHub)" <gi...@apache.org>.
LeonYoah commented on PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#issuecomment-3222415943

   The jsonpath util class might be extracted for use by kafka and the file connector


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2107261486


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/BracketJsonPathProcessor.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Processor for handling JsonPath with bracket notation (e.g., $['result']['value']). */
+public class BracketJsonPathProcessor extends AbstractJsonPathProcessor {
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {

Review Comment:
   Recheck the logic of `BracketJsonPathProcessor` and `ObjectJsonPathProcessor`. They are totally same. We can keep only one.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2125326996


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/BracketJsonPathProcessor.java:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Processor for handling JsonPath with bracket notation (e.g., $['result']['value']). */
+public class BracketJsonPathProcessor extends AbstractJsonPathProcessor {
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {

Review Comment:
   Yes, it is indeed redundant, and I have optimized the relevant code and implementation



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2080878270


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/AbstractJsonPathProcessor.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Abstract implementation of JsonPathProcessor providing common functionality. */
+public abstract class AbstractJsonPathProcessor implements JsonPathProcessor {
+
+    /** Flag to indicate whether to return null for missing fields */
+    private boolean jsonFiledMissedReturnNull = false;
+
+    /**
+     * Set whether to return null for missing fields.
+     *
+     * @param jsonFiledMissedReturnNull true to return null for missing fields, false otherwise
+     */
+    public void setJsonFiledMissedReturnNull(boolean jsonFiledMissedReturnNull) {
+        this.jsonFiledMissedReturnNull = jsonFiledMissedReturnNull;
+    }
+
+    /**
+     * Check if json fields with missing values should return null. This is used to determine
+     * whether to validate result consistency.
+     *
+     * @return true if missing fields should return null, false otherwise
+     */
+    protected boolean isJsonFiledMissedReturnNull() {
+        return jsonFiledMissedReturnNull;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String extractCommonParentPath(JsonPath[] paths);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String getRelativePath(String parentPath, String fullPath);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract boolean canProcess(String pathString);
+
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {
+        // Default implementation - can be overridden by subclasses
+        List<List<String>> results = new ArrayList<>(paths.length);
+
+        // Read all paths
+        for (JsonPath path : paths) {
+            results.add(jsonReadContext.read(path));
+        }
+
+        // Only validate consistency if jsonFiledMissedReturnNull is false
+        boolean shouldValidate = !isJsonFiledMissedReturnNull();
+        if (shouldValidate) {
+            validateResultsConsistency(results, paths);
+        }
+
+        return dataFlip(results);
+    }
+
+    /**
+     * Helper method to validate that all results have the same size.
+     *
+     * @param results The list of results to validate
+     * @param paths The JsonPath objects used to generate the results
+     * @throws HttpConnectorException if results are inconsistent
+     */
+    protected void validateResultsConsistency(List<List<String>> results, JsonPath[] paths) {
+        if (results.isEmpty()) {
+            return;
+        }
+
+        int expectedSize = results.get(0).size();
+        for (int i = 1; i < results.size(); i++) {
+            if (results.get(i).size() != expectedSize) {
+                throw new HttpConnectorException(
+                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                        String.format(
+                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
+                                paths[0].getPath(),
+                                expectedSize,
+                                paths[i].getPath(),
+                                results.get(i).size()));
+            }
+        }
+    }
+
+    /**
+     * Flips a matrix of results so that rows become columns and vice versa.
+     *
+     * @param results The original data matrix
+     * @return The flipped data matrix
+     */
+    protected List<List<String>> dataFlip(List<List<String>> results) {
+        List<List<String>> datas = new ArrayList<>();
+
+        for (int i = 0; i < results.size(); i++) {
+            List<String> result = results.get(i);
+            if (i == 0) {
+                for (Object o : result) {
+                    String val = o == null ? null : o.toString();
+                    List<String> row = new ArrayList<>(results.size());
+                    row.add(val);
+                    datas.add(row);
+                }
+            } else {
+                for (int j = 0; j < result.size(); j++) {
+                    Object o = result.get(j);
+                    String val = o == null ? null : o.toString();
+                    List<String> row = datas.get(j);
+                    row.add(val);
+                }
+            }
+        }
+
+        return datas;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractValue(ReadContext objContext, String relativePath) {
+        try {
+            Object value = objContext.read(relativePath);
+            if (value == null) {
+                return null;
+            }
+            if (value instanceof List) {
+                List<?> list = (List<?>) value;
+                return !list.isEmpty() ? list.get(0).toString() : null;

Review Comment:
   +1



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "hailin0 (via GitHub)" <gi...@apache.org>.
hailin0 commented on PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#issuecomment-2771289327

   Please add test cases


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "hailin0 (via GitHub)" <gi...@apache.org>.
hailin0 commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2026249019


##########
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-http-e2e/src/test/resources/http_to_console.conf:
##########
@@ -0,0 +1,61 @@
+#
+# 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.
+#
+######
+###### This config file is a demonstration of streaming processing in seatunnel config
+######
+
+env {
+  parallelism = 1
+  job.mode = "BATCH"
+}
+source{
+  Http {
+    url = "https://api-seller.ozon.ru/v2/finance/realization"

Review Comment:
   user mockserver mock api & response
   
   https://github.com/apache/seatunnel/blob/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-http-e2e/src/test/resources/github_json_to_assert.conf#L26
   https://github.com/apache/seatunnel/blob/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-http-e2e/src/test/resources/mockserver-config.json#L430



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2043417633


##########
seatunnel-connectors-v2/connector-http/connector-http-base/pom.xml:
##########
@@ -69,5 +71,35 @@
             <artifactId>json-path</artifactId>
             <version>${json-path.version}</version>
         </dependency>
+
+        <!-- Test dependencies -->
+        <dependency>
+            <groupId>org.junit.jupiter</groupId>
+            <artifactId>junit-jupiter-api</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.junit.jupiter</groupId>
+            <artifactId>junit-jupiter-engine</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <version>${mockito.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-junit-jupiter</artifactId>
+            <version>${mockito.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-json</artifactId>
+            <version>${hutool-json.version}</version>
+            <scope>test</scope>

Review Comment:
   Please do not introduce new json dependency. Just use jackson enough.



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -257,27 +257,139 @@ private List<Map<String, String>> parseToMap(List<List<String>> datas, JsonField
 
     private List<List<String>> decodeJSON(String data) {
         ReadContext jsonReadContext = JsonPath.using(jsonConfiguration).parse(data);
-        List<List<String>> results = new ArrayList<>(jsonPaths.length);
-        for (JsonPath path : jsonPaths) {
-            List<String> result = jsonReadContext.read(path);
-            results.add(result);
+
+        if (httpParameter.isJsonFiledMissedReturnNull()) {
+            // Extract the common parent path from all configured paths
+            String commonParentPath = extractCommonParentPath(jsonPaths);
+            if (commonParentPath == null) {
+                throw new HttpConnectorException(
+                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                        "Could not find common parent path in JsonPaths. All paths must share a common array parent.");
+            }
+
+            // Get all objects under the common parent path
+            List<Map<String, Object>> objects;
+            try {
+                objects = jsonReadContext.read(commonParentPath);
+            } catch (Exception e) {

Review Comment:
   The current implementation is a bit complicated.
   In fact, the jsonpath can do this by itself.  In jsonpath, https://github.com/apache/seatunnel/blob/d2ac555db1772cf58342db7709015a3b594aa87e/seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java#L64 we already enabled `DEFAULT_PATH_LEAF_TO_NULL`,
   ![image](https://github.com/user-attachments/assets/a9a187db-289b-46b5-aba4-0d133c48f01a)
   
   according the comment, when some path leaf not existed, it should return null. That's what we want, so we should check why this configure not work first.
   



##########
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-http-e2e/src/test/java/org/apache/seatunnel/e2e/connector/http/HttpIT.java:
##########
@@ -357,6 +357,9 @@ public void testSourceToAssertSink(TestContainer container)
         Container.ExecResult execResult19 =
                 container.executeJob("/http_page_increase_start_num.conf");
         Assertions.assertEquals(0, execResult19.getExitCode());
+
+        Container.ExecResult execResult21 = container.executeJob("/http_to_console.conf");
+        Assertions.assertEquals(0, execResult21.getExitCode());

Review Comment:
   Let's remove this e2e test case @ocean-zhc 



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2040677308


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -262,21 +262,41 @@ private List<List<String>> decodeJSON(String data) {
             List<String> result = jsonReadContext.read(path);
             results.add(result);
         }
-        for (int i = 1; i < results.size(); i++) {
-            List<?> result0 = results.get(0);
-            List<?> result = results.get(i);
-            if (result0.size() != result.size()) {
-                throw new HttpConnectorException(
-                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
-                        String.format(
-                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
-                                jsonPaths[0].getPath(),
-                                result0.size(),
-                                jsonPaths[i].getPath(),
-                                result.size()));
+        if (httpParameter.isJsonFiledMissedReturnNull()) {
+            int maxLength = 0;
+            for (List<?> result : results) {
+                maxLength = Math.max(maxLength, result.size());
+            }
+            for (int i = 0; i < results.size(); i++) {
+                List<String> result = results.get(i);
+                if (result.size() < maxLength) {
+                    log.warn(
+                            "Field [{}] with size ({}) is less than max size ({}), will be padded with null values. "
+                                    + "This may happen when JSON paths return different numbers of elements.",
+                            jsonPaths[i].getPath(),
+                            result.size(),
+                            maxLength);
+                    for (int j = result.size(); j < maxLength; j++) {
+                        result.add(null);
+                    }
+                }
+            }
+        } else {

Review Comment:
   Yes, it was indeed an issue and I didn't take into account the data correspondence, now I fixed it.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2051881368


##########
docs/en/connector-v2/source/Http.md:
##########
@@ -44,36 +44,34 @@ They can be downloaded via install-plugin.sh or from the Maven central repositor
 
 ## Source Options
 
-| Name                          |  Type   | Required | Default     | Description                                                                                                                                                                       |
-|-------------------------------|---------|----------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| url                           | String  | Yes      | -           | Http request url.                                                                                                                                                                 |
-| schema                        | Config  | No       | -           | Http and seatunnel data structure mapping                                                                                                                                         |
-| schema.fields                 | Config  | No       | -           | The schema fields of upstream data                                                                                                                                                |
-| json_field                    | Config  | No       | -           | This parameter helps you configure the schema,so this parameter must be used with schema.                                                                                         |
-| pageing                       | Config  | No       | -           | This parameter is used for paging queries                                                                                                                                         |
-| pageing.page_field            | String  | No       | -           | This parameter is used to specify the page field name in the request parameter                                                                                                    |
-| pageing.total_page_size       | Int     | No       | -           | This parameter is used to control the total number of pages                                                                                                                       |
-| pageing.batch_size            | Int     | No       | -           | The batch size returned per request is used to determine whether to continue when the total number of pages is unknown                                                            |
-| pageing.start_page_number     | Int     | No       | 1           | Specify the page number from which synchronization starts                                                                                                                         |
-| pageing.page_type             | String  | No       | PageNumber  | this parameter is used to specify the page type ,or PageNumber if not set, only support `PageNumber` and `Cursor`.                                  |

Review Comment:
   Please rebase on dev. You lose some change from #9109 



##########
docs/en/connector-v2/source/Http.md:
##########
@@ -366,14 +364,9 @@ source {
 - See this link for task configuration [http_jsonpath_to_assert.conf](../../../../seatunnel-e2e/seatunnel-connector-v2-e2e/connector-http-e2e/src/test/resources/http_jsonpath_to_assert.conf).
 
 ### pageing
-The current supported pagination type are `PageNumber` and `Cursor`. 

Review Comment:
   ditto



##########
docs/en/connector-v2/source/Http.md:
##########
@@ -44,36 +44,34 @@ They can be downloaded via install-plugin.sh or from the Maven central repositor
 
 ## Source Options
 
-| Name                          |  Type   | Required | Default     | Description                                                                                                                                                                       |
-|-------------------------------|---------|----------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| url                           | String  | Yes      | -           | Http request url.                                                                                                                                                                 |
-| schema                        | Config  | No       | -           | Http and seatunnel data structure mapping                                                                                                                                         |
-| schema.fields                 | Config  | No       | -           | The schema fields of upstream data                                                                                                                                                |
-| json_field                    | Config  | No       | -           | This parameter helps you configure the schema,so this parameter must be used with schema.                                                                                         |
-| pageing                       | Config  | No       | -           | This parameter is used for paging queries                                                                                                                                         |
-| pageing.page_field            | String  | No       | -           | This parameter is used to specify the page field name in the request parameter                                                                                                    |
-| pageing.total_page_size       | Int     | No       | -           | This parameter is used to control the total number of pages                                                                                                                       |
-| pageing.batch_size            | Int     | No       | -           | The batch size returned per request is used to determine whether to continue when the total number of pages is unknown                                                            |
-| pageing.start_page_number     | Int     | No       | 1           | Specify the page number from which synchronization starts                                                                                                                         |
-| pageing.page_type             | String  | No       | PageNumber  | this parameter is used to specify the page type ,or PageNumber if not set, only support `PageNumber` and `Cursor`.                                  |
-| pageing.cursor_field          | String  | No       | -           | this parameter is used to specify the Cursor field name in the request parameter.                                                                                       |
-| pageing.cursor_response_field | String  | No       | -           | This parameter specifies the field in the response from which the cursor is retrieved.                                                                                            |
-| content_json                  | String  | No       | -           | This parameter can get some json data.If you only need the data in the 'book' section, configure `content_field = "$.store.book.*"`.                                              |
-| format                        | String  | No       | text        | The format of upstream data, now only support `json` `text`, default `text`.                                                                                                      |
-| method                        | String  | No       | get         | Http request method, only supports GET, POST method.                                                                                                                              |
-| headers                       | Map     | No       | -           | Http headers.                                                                                                                                                                     |
-| params                        | Map     | No       | -           | Http params.                                                                                                                                                                      |
-| body                          | String  | No       | -           | Http body,the program will automatically add http header application/json,body is jsonbody.                                                                                       |
-| poll_interval_millis          | Int     | No       | -           | Request http api interval(millis) in stream mode.                                                                                                                                 |
-| retry                         | Int     | No       | -           | The max retry times if request http return to `IOException`.                                                                                                                      |
-| retry_backoff_multiplier_ms   | Int     | No       | 100         | The retry-backoff times(millis) multiplier if request http failed.                                                                                                                |
-| retry_backoff_max_ms          | Int     | No       | 10000       | The maximum retry-backoff times(millis) if request http failed                                                                                                                    |
-| enable_multi_lines            | Boolean | No       | false       |                                                                                                                                                                                   |
-| connect_timeout_ms            | Int     | No       | 12000       | Connection timeout setting, default 12s.                                                                                                                                          |
-| socket_timeout_ms             | Int     | No       | 60000       | Socket timeout setting, default 60s.                                                                                                                                              |
-| common-options                |         | No       | -           | Source plugin common parameters, please refer to [Source Common Options](../source-common-options.md) for details                                                                 |
-| keep_params_as_form           |    Boolean  | No       | false       | Whether the params are submitted according to the form, used for compatibility with legacy behaviors. When true, the value of the params parameter is submitted through the form. |
-| keep_page_param_as_http_param |    Boolean  | No       | false       | Whether to set the paging parameters to params. For compatibility with legacy behaviors.                                                                                          |
+|            Name             |  Type   | Required | Default | Description                                                                                                                                                                       |
+|-----------------------------|---------|----------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| url                         | String  | Yes      | -       | Http request url.                                                                                                                                                                 |
+| schema                      | Config  | No       | -       | Http and seatunnel data structure mapping                                                                                                                                         |
+| schema.fields               | Config  | No       | -       | The schema fields of upstream data                                                                                                                                                |
+| json_field                  | Config  | No       | -       | This parameter helps you configure the schema,so this parameter must be used with schema.                                                                                         |
+| pageing                     | Config  | No       | -       | This parameter is used for paging queries                                                                                                                                         |
+| pageing.page_field          | String  | No       | -       | This parameter is used to specify the page field name in the request parameter                                                                                                    |
+| pageing.total_page_size     | Int     | No       | -       | This parameter is used to control the total number of pages                                                                                                                       |
+| pageing.batch_size          | Int     | No       | -       | The batch size returned per request is used to determine whether to continue when the total number of pages is unknown                                                            |
+| pageing.start_page_number   | Int     | No       | 1       | Specify the page number from which synchronization starts                                                                                                                         |
+| content_json                | String  | No       | -       | This parameter can get some json data.If you only need the data in the 'book' section, configure `content_field = "$.store.book.*"`.                                              |
+| format                      | String  | No       | text    | The format of upstream data, now only support `json` `text`, default `text`.                                                                                                      |
+| method                      | String  | No       | get     | Http request method, only supports GET, POST method.                                                                                                                              |
+| headers                     | Map     | No       | -       | Http headers.                                                                                                                                                                     |
+| params                      | Map     | No       | -       | Http params.                                                                                                                                                                      |
+| body                        | String  | No       | -       | Http body,the program will automatically add http header application/json,body is jsonbody.                                                                                       |
+| poll_interval_millis        | Int     | No       | -       | Request http api interval(millis) in stream mode.                                                                                                                                 |
+| retry                       | Int     | No       | -       | The max retry times if request http return to `IOException`.                                                                                                                      |
+| retry_backoff_multiplier_ms | Int     | No       | 100     | The retry-backoff times(millis) multiplier if request http failed.                                                                                                                |
+| retry_backoff_max_ms        | Int     | No       | 10000   | The maximum retry-backoff times(millis) if request http failed                                                                                                                    |
+| enable_multi_lines          | Boolean | No       | false   |                                                                                                                                                                                   |
+| connect_timeout_ms          | Int     | No       | 12000   | Connection timeout setting, default 12s.                                                                                                                                          |
+| socket_timeout_ms           | Int     | No       | 60000   | Socket timeout setting, default 60s.                                                                                                                                              |
+| common-options              |         | No       | -       | Source plugin common parameters, please refer to [Source Common Options](../source-common-options.md) for details                                                                 |
+| keep_params_as_form         |    Boolean     | No       | false       | Whether the params are submitted according to the form, used for compatibility with legacy behaviors. When true, the value of the params parameter is submitted through the form. |
+| keep_page_param_as_http_param         |    Boolean     | No       | false       | Whether to set the paging parameters to params. For compatibility with legacy behaviors.|                                                                                                                          |
+| json_filed_missed_return_null         |    Boolean     | No       | false       | When the json field is missing, set true return null else error.|

Review Comment:
   we should tell users when should it be configured to true, and what are its limitations (as far as I know, all keys need to have the same array prefix).



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullTest.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpClientProvider;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpResponse;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpParameter;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpRequestMethod;
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.source.HttpSourceReader;
+import org.apache.seatunnel.connectors.seatunnel.http.source.SimpleTextDeserializationSchema;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class JsonFieldMissedReturnNullTest {
+
+    private HttpParameter httpParameter;
+    private JsonField jsonField;
+    private SimpleTextDeserializationSchema deserializationSchema;
+
+    @Mock private SingleSplitReaderContext context;
+
+    @Mock private Collector<SeaTunnelRow> collector;
+
+    @Mock private HttpClientProvider httpClientProvider;
+
+    @Mock private HttpResponse httpResponse;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+
+        httpParameter = new HttpParameter();
+        httpParameter.setUrl("http://test-url.com");
+        httpParameter.setMethod(HttpRequestMethod.GET);
+
+        Map<String, String> fields = new HashMap<>();
+        fields.put("key1", "$[*].key1");
+        fields.put("key2", "$[*].key2");
+        jsonField = JsonField.builder().fields(fields).build();
+
+        // Create the schema with two string fields
+        SeaTunnelRowType rowType =
+                new SeaTunnelRowType(
+                        new String[] {"key1", "key2"},
+                        new SeaTunnelDataType[] {BasicType.STRING_TYPE, BasicType.STRING_TYPE});
+        deserializationSchema = new SimpleTextDeserializationSchema(rowType);
+
+        // Setup mocks
+        when(httpResponse.getCode()).thenReturn(200);
+        when(collector.getCheckpointLock()).thenReturn(new Object());
+    }
+
+    @Test
+    public void testJsonFieldMissedReturnNull() throws Exception {
+        // Test data with missing fields
+        String testJsonData =
+                "[{\"key1\":\"value11\",\"key2\":\"value22\"},{\"key2\":\"value33\"},{\"key1\":\"value55\"}]";
+
+        // Set json_filed_missed_return_null to true
+        httpParameter.setJsonFiledMissedReturnNull(true);
+
+        // Setup HTTP response
+        when(httpResponse.getContent()).thenReturn(testJsonData);
+        when(httpClientProvider.execute(
+                        anyString(), anyString(), any(), any(), any(), any(Boolean.class)))
+                .thenReturn(httpResponse);
+
+        // Create HttpSourceReader
+        HttpSourceReader sourceReader =
+                new HttpSourceReader(
+                        httpParameter, context, deserializationSchema, jsonField, null);
+
+        // Use reflection to inject our mocked HTTP client
+        sourceReader.open(); // This creates the real HTTP client
+        Field httpClientField = HttpSourceReader.class.getDeclaredField("httpClient");
+        httpClientField.setAccessible(true);
+        httpClientField.set(sourceReader, httpClientProvider);
+
+        // Capture the rows collected
+        ArgumentCaptor<SeaTunnelRow> rowCaptor = ArgumentCaptor.forClass(SeaTunnelRow.class);
+
+        // Call the method that processes data
+        sourceReader.pollNext(collector);
+
+        // Verify collector.collect was called 3 times (once for each JSON object)

Review Comment:
   ```suggestion
           // Verify collector.collect was called 1 times (once for each JSON object)
   ```



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2085857747


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/AbstractJsonPathProcessor.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Abstract implementation of JsonPathProcessor providing common functionality. */
+public abstract class AbstractJsonPathProcessor implements JsonPathProcessor {
+
+    /** Flag to indicate whether to return null for missing fields */
+    private boolean jsonFiledMissedReturnNull = false;
+
+    /**
+     * Set whether to return null for missing fields.
+     *
+     * @param jsonFiledMissedReturnNull true to return null for missing fields, false otherwise
+     */
+    public void setJsonFiledMissedReturnNull(boolean jsonFiledMissedReturnNull) {
+        this.jsonFiledMissedReturnNull = jsonFiledMissedReturnNull;
+    }
+
+    /**
+     * Check if json fields with missing values should return null. This is used to determine
+     * whether to validate result consistency.
+     *
+     * @return true if missing fields should return null, false otherwise
+     */
+    protected boolean isJsonFiledMissedReturnNull() {
+        return jsonFiledMissedReturnNull;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String extractCommonParentPath(JsonPath[] paths);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String getRelativePath(String parentPath, String fullPath);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract boolean canProcess(String pathString);
+
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {
+        // Default implementation - can be overridden by subclasses
+        List<List<String>> results = new ArrayList<>(paths.length);
+
+        // Read all paths
+        for (JsonPath path : paths) {
+            results.add(jsonReadContext.read(path));
+        }
+
+        // Only validate consistency if jsonFiledMissedReturnNull is false
+        boolean shouldValidate = !isJsonFiledMissedReturnNull();
+        if (shouldValidate) {
+            validateResultsConsistency(results, paths);
+        }
+
+        return dataFlip(results);
+    }
+
+    /**
+     * Helper method to validate that all results have the same size.
+     *
+     * @param results The list of results to validate
+     * @param paths The JsonPath objects used to generate the results
+     * @throws HttpConnectorException if results are inconsistent
+     */
+    protected void validateResultsConsistency(List<List<String>> results, JsonPath[] paths) {
+        if (results.isEmpty()) {
+            return;
+        }
+
+        int expectedSize = results.get(0).size();
+        for (int i = 1; i < results.size(); i++) {
+            if (results.get(i).size() != expectedSize) {
+                throw new HttpConnectorException(
+                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                        String.format(
+                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
+                                paths[0].getPath(),
+                                expectedSize,
+                                paths[i].getPath(),
+                                results.get(i).size()));
+            }
+        }
+    }
+
+    /**
+     * Flips a matrix of results so that rows become columns and vice versa.
+     *
+     * @param results The original data matrix
+     * @return The flipped data matrix
+     */
+    protected List<List<String>> dataFlip(List<List<String>> results) {
+        List<List<String>> datas = new ArrayList<>();
+
+        for (int i = 0; i < results.size(); i++) {
+            List<String> result = results.get(i);
+            if (i == 0) {
+                for (Object o : result) {
+                    String val = o == null ? null : o.toString();
+                    List<String> row = new ArrayList<>(results.size());
+                    row.add(val);
+                    datas.add(row);
+                }
+            } else {
+                for (int j = 0; j < result.size(); j++) {
+                    Object o = result.get(j);
+                    String val = o == null ? null : o.toString();
+                    List<String> row = datas.get(j);
+                    row.add(val);
+                }
+            }
+        }
+
+        return datas;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractValue(ReadContext objContext, String relativePath) {
+        try {
+            Object value = objContext.read(relativePath);
+            if (value == null) {
+                return null;
+            }
+            if (value instanceof List) {
+                List<?> list = (List<?>) value;
+                return !list.isEmpty() ? list.toString() : null;

Review Comment:
   +1, use JsonString replace String



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w merged PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2077285103


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathUtils.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Utility class for JsonPath operations. */
+public class JsonPathUtils {
+
+    private static final Option[] DEFAULT_OPTIONS = {
+        Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST, Option.DEFAULT_PATH_LEAF_TO_NULL
+    };
+
+    private static final Configuration JSON_CONFIGURATION =
+            Configuration.defaultConfiguration().addOptions(DEFAULT_OPTIONS);
+
+    /**
+     * Creates a ReadContext from a JSON string.
+     *
+     * @param json The JSON string
+     * @return A ReadContext for the JSON
+     */
+    public static ReadContext parseJson(String json) {
+        return JsonPath.using(JSON_CONFIGURATION).parse(json);
+    }
+
+    /**
+     * Extracts data from JSON using JsonPaths.
+     *
+     * @param json The JSON string to parse
+     * @param jsonField The JsonField containing path mappings
+     * @param allowNullFields Whether to allow missing fields
+     * @return List of data extracted from JSON
+     */
+    public static List<Map<String, String>> extractData(
+            String json, JsonField jsonField, boolean allowNullFields) {
+        // Parse JSON into ReadContext
+        ReadContext jsonReadContext = parseJson(json);
+
+        // Convert JsonField to JsonPath array
+        JsonPath[] jsonPaths = createJsonPaths(jsonField);
+
+        // Get appropriate processor with jsonFiledMissedReturnNull flag
+        JsonPathProcessor processor =
+                JsonPathProcessorFactory.getProcessor(jsonPaths, allowNullFields);
+
+        // Process JSON data based on the processor
+        List<List<String>> results = processor.processJsonData(jsonReadContext, jsonPaths);
+
+        // Convert results to maps
+        return parseToMap(results, jsonField);
+    }
+
+    /**
+     * Creates JsonPath array from JsonField.
+     *
+     * @param jsonField The JsonField to convert
+     * @return Array of JsonPath objects
+     */
+    public static JsonPath[] createJsonPaths(JsonField jsonField) {
+        if (jsonField == null || jsonField.getFields() == null || jsonField.getFields().isEmpty()) {
+            throw new HttpConnectorException(
+                    HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                    "JsonField cannot be null or empty");
+        }
+
+        JsonPath[] jsonPaths = new JsonPath[jsonField.getFields().size()];
+        int index = 0;
+        for (String pathString : jsonField.getFields().values()) {
+            jsonPaths[index++] = JsonPath.compile(pathString);
+        }
+
+        return jsonPaths;
+    }
+
+    /**
+     * Converts parsed data to a list of maps.
+     *
+     * @param data The raw data (list of lists)
+     * @param jsonField The JsonField containing field names
+     * @return List of maps with field names as keys
+     */
+    public static List<Map<String, String>> parseToMap(
+            List<List<String>> data, JsonField jsonField) {
+        List<Map<String, String>> resultList = new ArrayList<>(data.size());
+        String[] keys = jsonField.getFields().keySet().toArray(new String[0]);
+
+        for (List<String> row : data) {
+            Map<String, String> resultMap = new HashMap<>(jsonField.getFields().size());
+            for (int i = 0; i < row.size(); i++) {
+                resultMap.put(keys[i], row.get(i));
+            }
+            resultList.add(resultMap);
+        }
+
+        return resultList;
+    }
+
+    /**
+     * Extracts the common parent path from JsonPaths.
+     *
+     * @param paths Array of JsonPath objects
+     * @return The common parent path
+     */
+    public static String extractCommonParentPath(JsonPath[] paths) {
+        return JsonPathProcessorFactory.getProcessor(paths).extractCommonParentPath(paths);
+    }
+
+    /**
+     * Gets a relative path from a parent path and a full path.
+     *
+     * @param parentPath The parent path
+     * @param fullPath The full path
+     * @return The relative path
+     */
+    public static String getRelativePath(String parentPath, String fullPath) {
+        return JsonPathProcessorFactory.getProcessor(fullPath)
+                .getRelativePath(parentPath, fullPath);
+    }

Review Comment:
   useless too?



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathUtils.java:
##########
@@ -0,0 +1,147 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/** Utility class for JsonPath operations. */
+public class JsonPathUtils {
+
+    private static final Option[] DEFAULT_OPTIONS = {
+        Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST, Option.DEFAULT_PATH_LEAF_TO_NULL
+    };
+
+    private static final Configuration JSON_CONFIGURATION =
+            Configuration.defaultConfiguration().addOptions(DEFAULT_OPTIONS);
+
+    /**
+     * Creates a ReadContext from a JSON string.
+     *
+     * @param json The JSON string
+     * @return A ReadContext for the JSON
+     */
+    public static ReadContext parseJson(String json) {
+        return JsonPath.using(JSON_CONFIGURATION).parse(json);
+    }
+
+    /**
+     * Extracts data from JSON using JsonPaths.
+     *
+     * @param json The JSON string to parse
+     * @param jsonField The JsonField containing path mappings
+     * @param allowNullFields Whether to allow missing fields
+     * @return List of data extracted from JSON
+     */
+    public static List<Map<String, String>> extractData(

Review Comment:
   useless?



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/source/HttpSourceReader.java:
##########
@@ -467,8 +447,8 @@ private String getPartOfJson(String data) {
     }
 
     private List<List<String>> dataFlip(List<List<String>> results) {

Review Comment:
   useless now?



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/AbstractJsonPathProcessor.java:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Abstract implementation of JsonPathProcessor providing common functionality. */
+public abstract class AbstractJsonPathProcessor implements JsonPathProcessor {
+
+    /** Flag to indicate whether to return null for missing fields */
+    private boolean jsonFiledMissedReturnNull = false;
+
+    /**
+     * Set whether to return null for missing fields.
+     *
+     * @param jsonFiledMissedReturnNull true to return null for missing fields, false otherwise
+     */
+    public void setJsonFiledMissedReturnNull(boolean jsonFiledMissedReturnNull) {
+        this.jsonFiledMissedReturnNull = jsonFiledMissedReturnNull;
+    }
+
+    /**
+     * Check if json fields with missing values should return null. This is used to determine
+     * whether to validate result consistency.
+     *
+     * @return true if missing fields should return null, false otherwise
+     */
+    protected boolean isJsonFiledMissedReturnNull() {
+        return jsonFiledMissedReturnNull;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String extractCommonParentPath(JsonPath[] paths);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract String getRelativePath(String parentPath, String fullPath);
+
+    /** {@inheritDoc} */
+    @Override
+    public abstract boolean canProcess(String pathString);
+
+    /** {@inheritDoc} */
+    @Override
+    public List<List<String>> processJsonData(ReadContext jsonReadContext, JsonPath[] paths) {
+        // Default implementation - can be overridden by subclasses
+        List<List<String>> results = new ArrayList<>(paths.length);
+
+        // Read all paths
+        for (JsonPath path : paths) {
+            results.add(jsonReadContext.read(path));
+        }
+
+        // Only validate consistency if jsonFiledMissedReturnNull is false
+        boolean shouldValidate = !isJsonFiledMissedReturnNull();
+        if (shouldValidate) {
+            validateResultsConsistency(results, paths);
+        }
+
+        return dataFlip(results);
+    }
+
+    /**
+     * Helper method to validate that all results have the same size.
+     *
+     * @param results The list of results to validate
+     * @param paths The JsonPath objects used to generate the results
+     * @throws HttpConnectorException if results are inconsistent
+     */
+    protected void validateResultsConsistency(List<List<String>> results, JsonPath[] paths) {
+        if (results.isEmpty()) {
+            return;
+        }
+
+        int expectedSize = results.get(0).size();
+        for (int i = 1; i < results.size(); i++) {
+            if (results.get(i).size() != expectedSize) {
+                throw new HttpConnectorException(
+                        HttpConnectorErrorCode.FIELD_DATA_IS_INCONSISTENT,
+                        String.format(
+                                "[%s](%d) and [%s](%d) the number of parsing records is inconsistent.",
+                                paths[0].getPath(),
+                                expectedSize,
+                                paths[i].getPath(),
+                                results.get(i).size()));
+            }
+        }
+    }
+
+    /**
+     * Flips a matrix of results so that rows become columns and vice versa.
+     *
+     * @param results The original data matrix
+     * @return The flipped data matrix
+     */
+    protected List<List<String>> dataFlip(List<List<String>> results) {
+        List<List<String>> datas = new ArrayList<>();
+
+        for (int i = 0; i < results.size(); i++) {
+            List<String> result = results.get(i);
+            if (i == 0) {
+                for (Object o : result) {
+                    String val = o == null ? null : o.toString();
+                    List<String> row = new ArrayList<>(results.size());
+                    row.add(val);
+                    datas.add(row);
+                }
+            } else {
+                for (int j = 0; j < result.size(); j++) {
+                    Object o = result.get(j);
+                    String val = o == null ? null : o.toString();
+                    List<String> row = datas.get(j);
+                    row.add(val);
+                }
+            }
+        }
+
+        return datas;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractValue(ReadContext objContext, String relativePath) {
+        try {
+            Object value = objContext.read(relativePath);
+            if (value == null) {
+                return null;
+            }
+            if (value instanceof List) {
+                List<?> list = (List<?>) value;
+                return !list.isEmpty() ? list.get(0).toString() : null;

Review Comment:
   I think return list string instead of return first element is a better choice.



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/ObjectJsonPathProcessor.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/** Processor for handling JsonPath with dot notation (standard object notation). */
+public class ObjectJsonPathProcessor extends AbstractJsonPathProcessor {
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean canProcess(String pathString) {
+        // Check if path uses dot notation and doesn't use array notation or bracket notation
+        return pathString.contains(".")
+                && !pathString.contains("[*]")
+                && !pathString.contains("['")
+                && !pathString.contains("[\"");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractCommonParentPath(JsonPath[] paths) {

Review Comment:
   useless too?



##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/test/java/org/apache/seatunnel/connectors/seatunnel/http/JsonFieldMissedReturnNullTest.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http;
+
+import org.apache.seatunnel.shade.com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.apache.seatunnel.api.source.Collector;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.connectors.seatunnel.common.source.SingleSplitReaderContext;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpClientProvider;
+import org.apache.seatunnel.connectors.seatunnel.http.client.HttpResponse;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpParameter;
+import org.apache.seatunnel.connectors.seatunnel.http.config.HttpRequestMethod;
+import org.apache.seatunnel.connectors.seatunnel.http.config.JsonField;
+import org.apache.seatunnel.connectors.seatunnel.http.source.HttpSourceReader;
+import org.apache.seatunnel.connectors.seatunnel.http.source.SimpleTextDeserializationSchema;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class JsonFieldMissedReturnNullTest {
+
+    private HttpParameter httpParameter;
+    private JsonField jsonField;
+    private SimpleTextDeserializationSchema deserializationSchema;
+
+    @Mock private SingleSplitReaderContext context;
+
+    @Mock private Collector<SeaTunnelRow> collector;
+
+    @Mock private HttpClientProvider httpClientProvider;
+
+    @Mock private HttpResponse httpResponse;
+
+    @BeforeEach
+    public void setUp() {
+        MockitoAnnotations.openMocks(this);
+
+        httpParameter = new HttpParameter();
+        httpParameter.setUrl("http://test-url.com");
+        httpParameter.setMethod(HttpRequestMethod.GET);
+
+        Map<String, String> fields = new HashMap<>();
+        fields.put("key1", "$.result.key1");
+        fields.put("key2", "$.result2.key2.key2");
+        jsonField = JsonField.builder().fields(fields).build();
+
+        // Create the schema with two string fields
+        SeaTunnelRowType rowType =
+                new SeaTunnelRowType(
+                        new String[] {"key1", "key2"},
+                        new SeaTunnelDataType[] {BasicType.STRING_TYPE, BasicType.STRING_TYPE});
+        deserializationSchema = new SimpleTextDeserializationSchema(rowType);
+
+        // Setup mocks
+        when(httpResponse.getCode()).thenReturn(200);
+        when(collector.getCheckpointLock()).thenReturn(new Object());
+    }
+
+    @Test
+    public void testJsonFieldMissedReturnNull() throws Exception {
+        // Test data with missing fields  Non-array, no common parent path
+        String testJsonData =
+                "{\n"
+                        + "  \"result\": {\n"
+                        + "    \"key1\": \"value1\"\n"
+                        + "  },\n"
+                        + "  \"result2\": {}\n"
+                        + "}";
+
+        // Set json_filed_missed_return_null to true
+        httpParameter.setJsonFiledMissedReturnNull(true);
+
+        // Setup HTTP response
+        when(httpResponse.getContent()).thenReturn(testJsonData);
+        when(httpClientProvider.execute(
+                        anyString(), anyString(), any(), any(), any(), any(Boolean.class)))
+                .thenReturn(httpResponse);
+
+        // Create HttpSourceReader
+        HttpSourceReader sourceReader =
+                new HttpSourceReader(
+                        httpParameter, context, deserializationSchema, jsonField, null);
+
+        // Use reflection to inject our mocked HTTP client
+        sourceReader.open(); // This creates the real HTTP client
+        Field httpClientField = HttpSourceReader.class.getDeclaredField("httpClient");
+        httpClientField.setAccessible(true);
+        httpClientField.set(sourceReader, httpClientProvider);

Review Comment:
   Let's use our reflection tool https://github.com/apache/seatunnel/blob/051d19c3a9b0b580532b5ef27ba01695ded2d048/seatunnel-common/src/main/java/org/apache/seatunnel/common/utils/ReflectionUtils.java#L79



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2041335418


##########
docs/en/connector-v2/source/Http.md:
##########
@@ -71,6 +71,8 @@ They can be downloaded via install-plugin.sh or from the Maven central repositor
 | common-options              |         | No       | -       | Source plugin common parameters, please refer to [Source Common Options](../source-common-options.md) for details                                                                 |
 | keep_params_as_form         |    Boolean     | No       | false       | Whether the params are submitted according to the form, used for compatibility with legacy behaviors. When true, the value of the params parameter is submitted through the form. |
 | keep_page_param_as_http_param         |    Boolean     | No       | false       | Whether to set the paging parameters to params. For compatibility with legacy behaviors.                                                                                                                                  |
+| json_filed_missed_return_null         |    Boolean     | No       | false       | When the json field is missing, set true return null else error.

Review Comment:
   ```suggestion
   | json_filed_missed_return_null         |    Boolean     | No       | false       | When the json field is missing, set true return null else error. |
   ```



##########
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-http-e2e/src/test/java/org/apache/seatunnel/e2e/connector/http/HttpIT.java:
##########
@@ -357,6 +357,9 @@ public void testSourceToAssertSink(TestContainer container)
         Container.ExecResult execResult19 =
                 container.executeJob("/http_page_increase_start_num.conf");
         Assertions.assertEquals(0, execResult19.getExitCode());
+
+        Container.ExecResult execResult21 = container.executeJob("/http_to_console.conf");
+        Assertions.assertEquals(0, execResult21.getExitCode());

Review Comment:
   I perfer use unit test to check it rather than e2e. Unit test can check all return value more easier. Current e2e test case you added even not check result data.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2085857417


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathProcessorFactory.java:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Factory for creating appropriate JsonPathProcessor instances based on the JsonPath format. */
+public class JsonPathProcessorFactory {
+
+    // List of all available processors
+    private static final List<JsonPathProcessor> PROCESSORS = new ArrayList<>();
+
+    static {
+        // Register all available processors in order of precedence
+        PROCESSORS.add(new ArrayJsonPathProcessor());
+        PROCESSORS.add(new BracketJsonPathProcessor());
+        PROCESSORS.add(new ObjectJsonPathProcessor());
+    }

Review Comment:
   +1 ,repaired



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2084553158


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/ObjectJsonPathProcessor.java:
##########
@@ -0,0 +1,152 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.http.exception.HttpConnectorException;
+
+import com.jayway.jsonpath.JsonPath;
+import com.jayway.jsonpath.ReadContext;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/** Processor for handling JsonPath with dot notation (standard object notation). */
+public class ObjectJsonPathProcessor extends AbstractJsonPathProcessor {
+
+    /** {@inheritDoc} */
+    @Override
+    public boolean canProcess(String pathString) {
+        // Check if path uses dot notation and doesn't use array notation or bracket notation
+        return pathString.contains(".")
+                && !pathString.contains("[*]")
+                && !pathString.contains("['")
+                && !pathString.contains("[\"");
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public String extractCommonParentPath(JsonPath[] paths) {

Review Comment:
   But it only used in `ArrayJsonPathProcessor`. Same as `getRelativePath`.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2084559623


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathProcessorFactory.java:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/** Factory for creating appropriate JsonPathProcessor instances based on the JsonPath format. */
+public class JsonPathProcessorFactory {
+
+    // List of all available processors
+    private static final List<JsonPathProcessor> PROCESSORS = new ArrayList<>();
+
+    static {
+        // Register all available processors in order of precedence
+        PROCESSORS.add(new ArrayJsonPathProcessor());
+        PROCESSORS.add(new BracketJsonPathProcessor());
+        PROCESSORS.add(new ObjectJsonPathProcessor());
+    }

Review Comment:
   JsonPathProcessor seem like not threadsafe. So use static instance not a good choice.



-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "ocean-zhc (via GitHub)" <gi...@apache.org>.
ocean-zhc commented on PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#issuecomment-2771361100

   > Please add test cases
   
   # 9093


-- 
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: commits-unsubscribe@seatunnel.apache.org

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


Re: [PR] [Fix][connector-http] fix parsing httpjson, the number of two fields is inconsistent with the import failure [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #9103:
URL: https://github.com/apache/seatunnel/pull/9103#discussion_r2297420267


##########
seatunnel-connectors-v2/connector-http/connector-http-base/src/main/java/org/apache/seatunnel/connectors/seatunnel/http/util/JsonPathProcessorFactory.java:
##########
@@ -0,0 +1,134 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.http.util;
+
+import com.jayway.jsonpath.JsonPath;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Supplier;
+
+/** Factory for creating appropriate JsonPathProcessor instances based on the JsonPath format. */
+public class JsonPathProcessorFactory {
+
+    // List of processor suppliers in order of precedence
+    private static final List<ProcessorMatcher> PROCESSOR_MATCHERS = new ArrayList<>();
+
+    static {
+        // Register all available processor matchers in order of precedence
+        PROCESSOR_MATCHERS.add(
+                new ProcessorMatcher(
+                        path -> path.contains("[*]"), () -> new ArrayJsonPathProcessor()));
+        PROCESSOR_MATCHERS.add(
+                new ProcessorMatcher(
+                        path -> true, // Default matcher
+                        () -> new JsonPathProcessorImpl()));
+    }
+
+    /**
+     * Get the appropriate processor for a single JsonPath.
+     *
+     * @param jsonPath The JsonPath to process
+     * @return The appropriate JsonPathProcessor
+     */
+    public static JsonPathProcessor getProcessor(JsonPath jsonPath) {
+        return getProcessor(jsonPath.getPath());
+    }
+
+    /**
+     * Get the appropriate processor for a JsonPath string.
+     *
+     * @param pathString The JsonPath string to process
+     * @return The appropriate JsonPathProcessor
+     */
+    public static JsonPathProcessor getProcessor(String pathString) {
+        for (ProcessorMatcher matcher : PROCESSOR_MATCHERS) {
+            if (matcher.matches(pathString)) {
+                return matcher.createProcessor();
+            }
+        }
+
+        // Default to JsonPathProcessorImpl if no other processor matches
+        return new JsonPathProcessorImpl();
+    }
+
+    /**
+     * Get the appropriate processor for an array of JsonPaths. This will choose a processor based
+     * on the first path in the array.
+     *
+     * @param paths Array of JsonPath objects
+     * @return The appropriate JsonPathProcessor
+     */
+    public static JsonPathProcessor getProcessor(JsonPath[] paths) {

Review Comment:
   useless?



-- 
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: commits-unsubscribe@seatunnel.apache.org

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