jmeter-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From pmoua...@apache.org
Subject svn commit: r1853058 - in /jmeter/trunk/src: core/org/apache/jmeter/resources/ protocol/http/org/apache/jmeter/protocol/http/gui/action/
Date Wed, 06 Feb 2019 10:23:03 GMT
Author: pmouawad
Date: Wed Feb  6 10:23:03 2019
New Revision: 1853058

URL: http://svn.apache.org/viewvc?rev=1853058&view=rev
Log:
Bug 62959 Ability to create an HTTP Request from a Curl command

Improvements:

- Allow updating Test Plan instead of creating a whole one
- Add a comment on HTTP Request saying it was created from cURL on date
Fixes:

- If !request.isCompressed, don't add gzip,deflate
Bugzilla Id: 62959

Modified:
    jmeter/trunk/src/core/org/apache/jmeter/resources/messages.properties
    jmeter/trunk/src/core/org/apache/jmeter/resources/messages_de.properties
    jmeter/trunk/src/core/org/apache/jmeter/resources/messages_fr.properties
    jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/gui/action/ParseCurlCommandAction.java

Modified: jmeter/trunk/src/core/org/apache/jmeter/resources/messages.properties
URL: http://svn.apache.org/viewvc/jmeter/trunk/src/core/org/apache/jmeter/resources/messages.properties?rev=1853058&r1=1853057&r2=1853058&view=diff
==============================================================================
--- jmeter/trunk/src/core/org/apache/jmeter/resources/messages.properties (original)
+++ jmeter/trunk/src/core/org/apache/jmeter/resources/messages.properties Wed Feb  6 10:23:03
2019
@@ -245,10 +245,10 @@ cssjquery_tester_button_test=Test
 cssjquery_tester_field=Selector\:
 cssjquery_tester_title=CSS Selector Tester
 csvread_file_file_name=CSV file to get values from | *alias
-curl_create_failure=Error creating test plan, error:{0}
-curl_create_request=Create Test plan
-curl_create_success=Successfully created test plan
-curl_import=Create Test plan from cURL
+curl_create_failure=Error creating HTTP Request, error:{0}
+curl_create_request=Create HTTP Request
+curl_create_success=Successfully created HTTP Request
+curl_import=Create HTTP Request from cURL
 curl_import_menu=Import from cURL (alpha)
 cut=Cut
 cut_paste_function=Function syntax\:

Modified: jmeter/trunk/src/core/org/apache/jmeter/resources/messages_de.properties
URL: http://svn.apache.org/viewvc/jmeter/trunk/src/core/org/apache/jmeter/resources/messages_de.properties?rev=1853058&r1=1853057&r2=1853058&view=diff
==============================================================================
--- jmeter/trunk/src/core/org/apache/jmeter/resources/messages_de.properties (original)
+++ jmeter/trunk/src/core/org/apache/jmeter/resources/messages_de.properties Wed Feb  6 10:23:03
2019
@@ -111,6 +111,10 @@ counter_config_title=Zähler (Counter)
 counter_per_user=Zähler (Counter) für jeden Benutzer einzeln führen
 countlim=Größen-Beschränkung
 csvread_file_file_name=CSV Datei aus der die Werte gelesen werden | *alias
+curl_create_failure=Fehler beim Erstellen eines HTTP-Requests, Fehler:{0}
+curl_create_request=HTTP-Anfrage erstellen
+curl_create_success=Erfolgreich erstellte HTTP-Anfrage
+curl_import=HTTP-Request von cURL erzeugen
 cut=Ausschneiden
 cut_paste_function=Kopieren und Einfügen des Funktions Strings
 database_conn_pool_max_usage=Maximale Auslastung jeder Verbindung\:

Modified: jmeter/trunk/src/core/org/apache/jmeter/resources/messages_fr.properties
URL: http://svn.apache.org/viewvc/jmeter/trunk/src/core/org/apache/jmeter/resources/messages_fr.properties?rev=1853058&r1=1853057&r2=1853058&view=diff
==============================================================================
--- jmeter/trunk/src/core/org/apache/jmeter/resources/messages_fr.properties (original)
+++ jmeter/trunk/src/core/org/apache/jmeter/resources/messages_fr.properties Wed Feb  6 10:23:03
2019
@@ -240,10 +240,10 @@ cssjquery_tester_error=Une erreur s''est
 cssjquery_tester_field=Sélecteur\:
 cssjquery_tester_title=Testeur Selecteur CSS
 csvread_file_file_name=Fichier CSV pour obtenir les valeurs de | *alias
-curl_create_failure=Erreur de création de plan de test, erreur:{0}.
-curl_create_request=Créer plan de test
-curl_create_success=Plan de test créé avec succès
-curl_import=Créer un plan de test à partir de cURL
+curl_create_failure=Erreur de création de la requête HTTP, erreur:{0}.
+curl_create_request=Créer une requête HTTP
+curl_create_success=Requête HTTP créée avec succès
+curl_import=Créer une requête HTTP à partir de cURL
 curl_import_menu=Importer de cURL (alpha)
 cut=Couper
 cut_paste_function=Syntaxe de la fonction \:

Modified: jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/gui/action/ParseCurlCommandAction.java
URL: http://svn.apache.org/viewvc/jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/gui/action/ParseCurlCommandAction.java?rev=1853058&r1=1853057&r2=1853058&view=diff
==============================================================================
--- jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/gui/action/ParseCurlCommandAction.java
(original)
+++ jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/gui/action/ParseCurlCommandAction.java
Wed Feb  6 10:23:03 2019
@@ -28,6 +28,8 @@ import java.awt.event.KeyEvent;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.text.MessageFormat;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -42,7 +44,9 @@ import javax.swing.SwingUtilities;
 import javax.swing.tree.TreePath;
 
 import org.apache.jmeter.config.Arguments;
+import org.apache.jmeter.control.Controller;
 import org.apache.jmeter.control.LoopController;
+import org.apache.jmeter.control.ReplaceableController;
 import org.apache.jmeter.control.gui.TestPlanGui;
 import org.apache.jmeter.exceptions.IllegalUserActionException;
 import org.apache.jmeter.gui.GuiPackage;
@@ -50,6 +54,7 @@ import org.apache.jmeter.gui.action.Abst
 import org.apache.jmeter.gui.action.ActionNames;
 import org.apache.jmeter.gui.action.ActionRouter;
 import org.apache.jmeter.gui.plugin.MenuCreator;
+import org.apache.jmeter.gui.tree.JMeterTreeModel;
 import org.apache.jmeter.gui.tree.JMeterTreeNode;
 import org.apache.jmeter.gui.util.EscapeDialog;
 import org.apache.jmeter.gui.util.JSyntaxTextArea;
@@ -66,6 +71,7 @@ import org.apache.jmeter.reporters.Resul
 import org.apache.jmeter.services.FileServer;
 import org.apache.jmeter.testelement.TestElement;
 import org.apache.jmeter.testelement.TestPlan;
+import org.apache.jmeter.threads.AbstractThreadGroup;
 import org.apache.jmeter.threads.ThreadGroup;
 import org.apache.jmeter.threads.gui.ThreadGroupGui;
 import org.apache.jmeter.util.JMeterUtils;
@@ -103,7 +109,6 @@ public class ParseCurlCommandAction exte
 
     @Override
     public void doAction(ActionEvent e) {
-        ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(),
ActionNames.CLOSE));
         showInputDialog();
     }
     
@@ -133,8 +138,24 @@ public class ParseCurlCommandAction exte
         ComponentUtil.centerComponentInComponent(GuiPackage.getInstance().getMainFrame(),
messageDialog);
         SwingUtilities.invokeLater(() -> messageDialog.setVisible(true));
     }
+    
+    /**
+     * Finds the first enabled node of a given type in the tree.
+     *
+     * @param type      class of the node to be found
+     * @return the first node of the given type in the test component tree, or
+     * <code>null</code> if none was found.
+     */
+    private JMeterTreeNode findFirstNodeOfType(Class<?> type) {
+        JMeterTreeModel treeModel = GuiPackage.getInstance().getTreeModel();
+        return treeModel.getNodesOfType(type).stream()
+                .filter(JMeterTreeNode::isEnabled)
+                .findFirst()
+                .orElse(null);
+    }
 
     private void createTestPlan(ActionEvent e, Request request) throws MalformedURLException,
IllegalUserActionException {
+        ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(),
ActionNames.CLOSE));
         GuiPackage guiPackage = GuiPackage.getInstance();
 
         guiPackage.clearTestPlan();
@@ -183,20 +204,49 @@ public class ParseCurlCommandAction exte
     }
     
     private HTTPSamplerProxy createHttpRequest(Request request, HashTree parentHT) throws
MalformedURLException {
+        HTTPSamplerProxy httpSampler = createSampler(request);
+
+        HashTree samplerHT = parentHT.add(httpSampler);
+        samplerHT.add(httpSampler.getHeaderManager());
+        return httpSampler;
+    }
+
+    /**
+     * @param request {@link Request}
+     * @return {@link HTTPSamplerProxy}
+     * @throws MalformedURLException
+     */
+    private HTTPSamplerProxy createSampler(Request request) throws MalformedURLException
{
         HTTPSamplerProxy httpSampler = (HTTPSamplerProxy) HTTPSamplerFactory.newInstance(HTTPSamplerFactory.DEFAULT_CLASSNAME);
         httpSampler.setProperty(TestElement.GUI_CLASS, HttpTestSampleGui.class.getName());
         httpSampler.setProperty(TestElement.NAME, "HTTP Request");
+        httpSampler.setProperty(TestElement.COMMENTS, "Created from cURL on "+LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
         httpSampler.setProtocol(new URL(request.getUrl()).getProtocol());
         httpSampler.setPath(request.getUrl());
         httpSampler.setUseKeepAlive(true);
         httpSampler.setFollowRedirects(true);
         httpSampler.setMethod(request.getMethod());
+        if (!"GET".equals(request.getMethod())) {
+            Arguments arguments = new Arguments();
+            httpSampler.setArguments(arguments);
+            httpSampler.addNonEncodedArgument("", request.getPostData(), "");
+        }
         
-        HashTree samplerHT = parentHT.add(httpSampler);
-        
+        HeaderManager headerManager = createHeaderManager(request);
+        httpSampler.addTestElement(headerManager);
+
+        return httpSampler;
+    }
+
+    /**
+     * @param request {@link Request}
+     * @return {@link HeaderManager} element
+     */
+    private HeaderManager createHeaderManager(Request request) {
         HeaderManager headerManager = new HeaderManager();
         headerManager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());
         headerManager.setProperty(TestElement.NAME, "HTTP HeaderManager");
+        headerManager.setProperty(TestElement.COMMENTS, "Created from cURL on "+LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
         Map<String, String> map = request.getHeaders();
         
         boolean hasAcceptEncoding = false;
@@ -205,17 +255,10 @@ public class ParseCurlCommandAction exte
             hasAcceptEncoding = hasAcceptEncoding || key.equalsIgnoreCase(ACCEPT_ENCODING);
             headerManager.getHeaders().addItem(new Header(key, header.getValue()));
         }
-        if(!hasAcceptEncoding) {
+        if(!hasAcceptEncoding && request.isCompressed()) {
             headerManager.getHeaders().addItem(new Header(ACCEPT_ENCODING, "gzip, deflate"));
         }
-        if (!"GET".equals(request.getMethod())) {
-            Arguments arguments = new Arguments();
-            httpSampler.setArguments(arguments);
-            httpSampler.addNonEncodedArgument("", request.getPostData(), "");
-        }
-        httpSampler.addTestElement(headerManager);
-        samplerHT.add(headerManager);
-        return httpSampler;
+        return headerManager;
     }
 
     @Override
@@ -265,7 +308,22 @@ public class ParseCurlCommandAction exte
                 LOGGER.info("Parsed CURL command {} into {}", curlCommand, request);
                 GuiPackage guiPackage = GuiPackage.getInstance();
                 guiPackage.updateCurrentNode();
-                createTestPlan(e, request);
+                JMeterTreeNode treeNode = findFirstNodeOfType(AbstractThreadGroup.class);
+                if(treeNode == null) {
+                    LOGGER.info("No AbstractThreadGroup found, potentially empty plan, creating
a new plan");
+                    createTestPlan(e, request);
+                } else {
+                    JMeterTreeNode currentNode = guiPackage.getCurrentNode();
+                    Object userObject = currentNode.getUserObject();
+                    if (userObject instanceof Controller &&
+                            ! (userObject instanceof ReplaceableController)) {
+                        LOGGER.info("Newly created element will be placed under current selected
node {}", currentNode.getName());
+                        addToTestPlan(currentNode, request);
+                    } else {
+                        LOGGER.info("Newly created element will be placed under first AbstractThreadGroup
node {}", treeNode.getName());
+                        addToTestPlan(treeNode, request);
+                    }
+                }
                 statusText.setText(JMeterUtils.getResString("curl_create_success"));
             } catch (Exception ex) {
                 LOGGER.error("Error creating test plan from cURL command:{}, error:{}", curlCommand,
ex.getMessage(), ex);
@@ -274,4 +332,22 @@ public class ParseCurlCommandAction exte
             }
         }
     }
+
+    private void addToTestPlan(final JMeterTreeNode currentNode, Request request) 
+            throws MalformedURLException {
+        final HTTPSamplerProxy sampler = createSampler(request);
+        JMeterTreeModel treeModel = GuiPackage.getInstance().getTreeModel();
+        JMeterUtils.runSafe(true, () -> {
+            try {
+                // We get the HeaderManager before adding component otherwise addComponent
would remove it 
+                HeaderManager headerManager = sampler.getHeaderManager();
+                // 
+                final JMeterTreeNode newNode = treeModel.addComponent(sampler, currentNode);
+                treeModel.addComponent(headerManager, newNode);
+            } catch (IllegalUserActionException ex) {
+                LOGGER.error("Error placing sampler", ex);
+                JMeterUtils.reportErrorToUser(ex.getMessage());
+            }
+        });
+    }
 }



Mime
View raw message