milamberspace commented on code in PR #6736:
URL: https://github.com/apache/jmeter/pull/6736#discussion_r3650826320


##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java:
##########
@@ -0,0 +1,168 @@
+/*
+ * 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.jmeter.protocol.http.visualizers;
+
+import java.awt.BorderLayout;
+import java.net.URL;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import javax.swing.JPanel;
+
+import org.apache.jmeter.gui.util.JSyntaxSearchToolBar;
+import org.apache.jmeter.gui.util.JSyntaxTextArea;
+import org.apache.jmeter.gui.util.JTextScrollPane;
+import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
+import org.apache.jmeter.protocol.http.util.HTTPConstants;
+import org.apache.jmeter.util.JMeterUtils;
+import org.apache.jmeter.visualizers.RequestView;
+import org.apache.jorphan.util.StringUtilities;
+
+import com.google.auto.service.AutoService;
+
+/**
+ * Panel that renders an HTTP request as a ready-to-run {@code curl} command,
+ * so it can be copied and pasted into a console or shared with a developer.
+ */
+@AutoService(RequestView.class)
+public class RequestViewCurl implements RequestView {
+
+    // Used by Request Panel
+    static final String KEY_LABEL = "view_results_table_request_tab_curl"; 
//$NON-NLS-1$
+
+    private static final String NEWLINE = " \\\n"; //$NON-NLS-1$
+
+    /**
+     * Headers that must not be reproduced in the curl command: curl generates
+     * them itself, or they are connection-specific (hop-by-hop) headers that 
are
+     * forbidden in HTTP/2 and would make the request fail with a protocol 
error.
+     */
+    private static final Set<String> SKIPPED_HEADERS = Set.of(
+            "content-length", //$NON-NLS-1$
+            "connection", //$NON-NLS-1$
+            "keep-alive", //$NON-NLS-1$
+            "proxy-connection", //$NON-NLS-1$
+            "transfer-encoding", //$NON-NLS-1$
+            "upgrade"); //$NON-NLS-1$
+
+    private JSyntaxTextArea curlData;
+
+    private JPanel panel;
+
+    @Override
+    public void init() {
+        panel = new JPanel(new BorderLayout(0, 5));
+        curlData = JSyntaxTextArea.getInstance(20, 80, true);
+        curlData.setEditable(false);
+        curlData.setLineWrap(true);
+        curlData.setWrapStyleWord(true);
+        panel.add(new JSyntaxSearchToolBar(curlData).getToolBar(), 
BorderLayout.NORTH);
+        panel.add(JTextScrollPane.getInstance(curlData), BorderLayout.CENTER);
+    }
+
+    @Override
+    public void clearData() {
+        curlData.setInitialText(""); //$NON-NLS-1$
+    }
+
+    @Override
+    public void setSamplerResult(Object objectResult) {
+        if (objectResult instanceof HTTPSampleResult sampleResult) {
+            curlData.setInitialText(buildCurlCommand(sampleResult));
+            curlData.setCaretPosition(0);
+        } else {
+            // add a message when no http sample (ex. Java request)
+            
curlData.setInitialText(JMeterUtils.getResString("view_results_table_request_http_nohttp"));
 //$NON-NLS-1$
+        }
+    }
+
+    /**
+     * Build a {@code curl} command line that reproduces the given HTTP 
request.
+     *
+     * @param sampleResult the sampled HTTP request
+     * @return the curl command as a string
+     */
+    static String buildCurlCommand(HTTPSampleResult sampleResult) {
+        StringBuilder sb = new StringBuilder(256);
+        sb.append("curl"); //$NON-NLS-1$
+
+        String method = sampleResult.getHTTPMethod();
+        if (StringUtilities.isNotBlank(method)) {
+            sb.append(" -X ").append(quote(method)); //$NON-NLS-1$

Review Comment:
   **Consider dropping `-X` for GET.** `-X` is emitted unconditionally, so a 
plain GET renders as `curl -X 'GET' ...`. It is harmless but noisy; most curl 
generators omit `-X` for a GET with no body. Consider only emitting `-X` when 
the method is not GET (or when a body is present).



##########
src/protocol/http/src/main/java/org/apache/jmeter/protocol/http/visualizers/RequestViewCurl.java:
##########
@@ -0,0 +1,168 @@
+/*
+ * 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.jmeter.protocol.http.visualizers;
+
+import java.awt.BorderLayout;
+import java.net.URL;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import javax.swing.JPanel;
+
+import org.apache.jmeter.gui.util.JSyntaxSearchToolBar;
+import org.apache.jmeter.gui.util.JSyntaxTextArea;
+import org.apache.jmeter.gui.util.JTextScrollPane;
+import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult;
+import org.apache.jmeter.protocol.http.util.HTTPConstants;
+import org.apache.jmeter.util.JMeterUtils;
+import org.apache.jmeter.visualizers.RequestView;
+import org.apache.jorphan.util.StringUtilities;
+
+import com.google.auto.service.AutoService;
+
+/**
+ * Panel that renders an HTTP request as a ready-to-run {@code curl} command,
+ * so it can be copied and pasted into a console or shared with a developer.
+ */
+@AutoService(RequestView.class)
+public class RequestViewCurl implements RequestView {
+
+    // Used by Request Panel
+    static final String KEY_LABEL = "view_results_table_request_tab_curl"; 
//$NON-NLS-1$
+
+    private static final String NEWLINE = " \\\n"; //$NON-NLS-1$
+
+    /**
+     * Headers that must not be reproduced in the curl command: curl generates
+     * them itself, or they are connection-specific (hop-by-hop) headers that 
are
+     * forbidden in HTTP/2 and would make the request fail with a protocol 
error.
+     */
+    private static final Set<String> SKIPPED_HEADERS = Set.of(
+            "content-length", //$NON-NLS-1$
+            "connection", //$NON-NLS-1$
+            "keep-alive", //$NON-NLS-1$
+            "proxy-connection", //$NON-NLS-1$
+            "transfer-encoding", //$NON-NLS-1$
+            "upgrade"); //$NON-NLS-1$
+
+    private JSyntaxTextArea curlData;
+
+    private JPanel panel;
+
+    @Override
+    public void init() {
+        panel = new JPanel(new BorderLayout(0, 5));
+        curlData = JSyntaxTextArea.getInstance(20, 80, true);
+        curlData.setEditable(false);
+        curlData.setLineWrap(true);
+        curlData.setWrapStyleWord(true);
+        panel.add(new JSyntaxSearchToolBar(curlData).getToolBar(), 
BorderLayout.NORTH);
+        panel.add(JTextScrollPane.getInstance(curlData), BorderLayout.CENTER);
+    }
+
+    @Override
+    public void clearData() {
+        curlData.setInitialText(""); //$NON-NLS-1$
+    }
+
+    @Override
+    public void setSamplerResult(Object objectResult) {
+        if (objectResult instanceof HTTPSampleResult sampleResult) {
+            curlData.setInitialText(buildCurlCommand(sampleResult));
+            curlData.setCaretPosition(0);
+        } else {
+            // add a message when no http sample (ex. Java request)
+            
curlData.setInitialText(JMeterUtils.getResString("view_results_table_request_http_nohttp"));
 //$NON-NLS-1$
+        }
+    }
+
+    /**
+     * Build a {@code curl} command line that reproduces the given HTTP 
request.
+     *
+     * @param sampleResult the sampled HTTP request
+     * @return the curl command as a string
+     */
+    static String buildCurlCommand(HTTPSampleResult sampleResult) {
+        StringBuilder sb = new StringBuilder(256);
+        sb.append("curl"); //$NON-NLS-1$
+
+        String method = sampleResult.getHTTPMethod();
+        if (StringUtilities.isNotBlank(method)) {
+            sb.append(" -X ").append(quote(method)); //$NON-NLS-1$
+        }
+
+        URL url = sampleResult.getURL();
+        if (url != null) {
+            sb.append(NEWLINE).append("  ").append(quote(url.toString()));
+        }
+
+        boolean hasCookieHeader = false;
+        String requestHeaders = sampleResult.getRequestHeaders();
+        if (StringUtilities.isNotEmpty(requestHeaders)) {
+            LinkedHashMap<String, String> headers = 
JMeterUtils.parseHeaders(requestHeaders);
+            for (Map.Entry<String, String> entry : headers.entrySet()) {
+                String name = entry.getKey();
+                if (StringUtilities.isBlank(name) || 
SKIPPED_HEADERS.contains(name.toLowerCase(Locale.ROOT))) {
+                    continue;
+                }
+                if (HTTPConstants.HEADER_COOKIE.equalsIgnoreCase(name)) {
+                    hasCookieHeader = true;
+                }
+                sb.append(NEWLINE).append("  -H ").append(quote(name + ": " + 
entry.getValue())); //$NON-NLS-1$
+            }
+        }
+
+        // Cookies are tracked separately in JMeter; only add them if they were
+        // not already emitted as a Cookie header above.
+        String cookies = sampleResult.getCookies();
+        if (!hasCookieHeader && StringUtilities.isNotEmpty(cookies)) {
+            sb.append(NEWLINE).append("  -b ").append(quote(cookies)); 
//$NON-NLS-1$
+        }
+
+        String body = sampleResult.getQueryString();
+        if (StringUtilities.isNotBlank(body)) {
+            sb.append(NEWLINE).append("  --data-raw ").append(quote(body)); 
//$NON-NLS-1$

Review Comment:
   **Multipart / file-upload requests render a broken curl command.**
   
   `getQueryString()` is not the real wire body for `multipart/form-data`: it 
is JMeter's rendered representation, and for file uploads it contains the 
literal placeholder `<actual file content, not shown here>` (see 
`HTTPHC4Impl.writeEntityToSB` / `PostWriter`, fed into the query string at 
`HTTPHC4Impl#883`). Since the `Content-Type: multipart/form-data; boundary=...` 
header is kept and this value is emitted verbatim via `--data-raw`, a sampled 
file upload produces:
   
   ```
   --data-raw '...--boundary...<actual file content, not shown here>...'
   ```
   
   Pasted into a terminal this sends the placeholder text instead of the file 
bytes, so the request is not reproduced. This is exactly the case 
`RequestViewHTTP` special-cases via `isMultipart(...)`. Suggestion: detect 
multipart requests and either skip `--data-raw` or replace it with a short 
note, rather than emit a silently-wrong command.



##########
xdocs/changes.xml:
##########
@@ -104,6 +104,7 @@ Summary
   <ul>
     <li><pr>6333</pr>Apply HiDPI mode automatically when setting up the GUI so 
JMeter looks sharp on high-resolution displays. Contributed by Gabriele Coletta 
(github.com/gdmg92)</li>
     <li><pr>6656</pr>Replace the previous feather icon with the new oak leaf 
in the JMeter logo.</li>
+    <li><issue>6375</issue>Add a <code>cURL</code> tab to the Request panel in 
View Results Tree, showing the sampled HTTP request as a ready-to-run 
<code>curl</code> command that can be copied to a console. Contributed by 
Oleksandr Poliakov (github.com/poliakov-alex)</li>

Review Comment:
   This entry uses `<issue>6375</issue>` but no `<pr>` tag. Other entries in 
the section reference the PR number (often alongside the issue); consider 
adding `<pr>6736</pr>` for traceability.



##########
xdocs/usermanual/component_reference.xml:
##########
@@ -2798,6 +2798,8 @@ response for any sample.  In addition to showing the 
response, you can see the t
 this response, and some response codes.
 Note that the Request panel only shows the headers added by JMeter.
 It does not show any headers (such as <code>Host</code>) that may be added by 
the HTTP protocol implementation.
+For HTTP samples the Request panel also provides a <code>cURL</code> tab that 
renders the request as a
+ready-to-run <code>curl</code> command, so it can be copied to a console or 
shared with a developer.

Review Comment:
   Nice that the doc is updated here. Consider adding one sentence noting that 
multipart / file-upload requests cannot be reproduced faithfully (the file 
content is not captured by JMeter), so users are not surprised when such a 
command fails — see the related note on `RequestViewCurl`.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to