Search in sources :

Example 1 with InvalidVariableException

use of org.apache.jmeter.functions.InvalidVariableException in project jmeter by apache.

the class ProxyControl method addTimers.

/**
 * Helper method to replicate any timers found within the Proxy Controller
 * into the provided sampler, while replacing any occurrences of string _T_
 * in the timer's configuration with the provided deltaT.
 * Called from AWT Event thread
 *
 * @param model  Test component tree model
 * @param node   Sampler node in where we will add the timers
 * @param deltaT Time interval from the previous request
 */
@SuppressWarnings("JdkObsolete")
private void addTimers(JMeterTreeModel model, JMeterTreeNode node, long deltaT) {
    TestPlan variables = new TestPlan();
    // $NON-NLS-1$
    variables.addParameter("T", Long.toString(deltaT));
    ValueReplacer replacer = new ValueReplacer(variables);
    JMeterTreeNode mySelf = model.getNodeOf(this);
    if (mySelf != null) {
        Enumeration<?> children = mySelf.children();
        while (children.hasMoreElements()) {
            JMeterTreeNode templateNode = (JMeterTreeNode) children.nextElement();
            if (templateNode.isEnabled()) {
                TestElement template = templateNode.getTestElement();
                if (template instanceof Timer) {
                    TestElement timer = (TestElement) template.clone();
                    try {
                        timer.setComment("Recorded:" + Long.toString(deltaT) + "ms");
                        replacer.undoReverseReplace(timer);
                        model.addComponent(timer, node);
                    } catch (InvalidVariableException | IllegalUserActionException e) {
                        // Not 100% sure, but I believe this can't happen, so
                        // I'll log and throw an error:
                        log.error("Program error adding timers", e);
                        throw new Error(e);
                    }
                }
            }
        }
    }
}
Also used : InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) Timer(org.apache.jmeter.timers.Timer) TestPlan(org.apache.jmeter.testelement.TestPlan) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) IllegalUserActionException(org.apache.jmeter.exceptions.IllegalUserActionException) ValueReplacer(org.apache.jmeter.engine.util.ValueReplacer) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) NonTestElement(org.apache.jmeter.testelement.NonTestElement)

Example 2 with InvalidVariableException

use of org.apache.jmeter.functions.InvalidVariableException in project jmeter by apache.

the class PreCompiler method addNode.

/**
 * {@inheritDoc}
 */
@Override
public void addNode(Object node, HashTree subTree) {
    if (isClientSide) {
        if (node instanceof ResultCollector || node instanceof Backend) {
            try {
                replacer.replaceValues((TestElement) node);
            } catch (InvalidVariableException e) {
                log.error("invalid variables in node {}", ((TestElement) node).getName(), e);
            }
        }
        if (node instanceof TestPlan) {
            this.clientSideVariables = createVars((TestPlan) node);
        }
        if (node instanceof Arguments) {
            // Don't store User Defined Variables in the context for client side
            Map<String, String> args = createArgumentsMap((Arguments) node);
            clientSideVariables.putAll(args);
        }
    } else {
        if (node instanceof TestElement) {
            try {
                replacer.replaceValues((TestElement) node);
            } catch (InvalidVariableException e) {
                log.error("invalid variables in node {}", ((TestElement) node).getName(), e);
            }
        }
        if (node instanceof TestPlan) {
            JMeterVariables vars = createVars((TestPlan) node);
            JMeterContextService.getContext().setVariables(vars);
        }
        if (node instanceof Arguments) {
            Map<String, String> args = createArgumentsMap((Arguments) node);
            JMeterContextService.getContext().getVariables().putAll(args);
        }
    }
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) Backend(org.apache.jmeter.visualizers.backend.Backend) InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) TestPlan(org.apache.jmeter.testelement.TestPlan) Arguments(org.apache.jmeter.config.Arguments) TestElement(org.apache.jmeter.testelement.TestElement) ResultCollector(org.apache.jmeter.reporters.ResultCollector)

Example 3 with InvalidVariableException

use of org.apache.jmeter.functions.InvalidVariableException in project jmeter by apache.

the class FunctionParser method makeFunction.

/**
 * Compile a string into a function or SimpleVariable.
 *
 * Called by {@link #compileString(String)} when that has detected "${".
 *
 * Calls {@link CompoundVariable#getNamedFunction(String)} if it detects:
 * '(' - start of parameter list
 * '}' - end of function call
 *
 * @param reader points to input after the "${"
 * @return the function or variable object (or a String)
 * @throws InvalidVariableException when evaluation of variables fail
 */
Object makeFunction(StringReader reader) throws InvalidVariableException {
    char[] current = new char[1];
    // TODO - why use space?
    char previous = ' ';
    StringBuilder buffer = new StringBuilder();
    Object function;
    try {
        while (reader.read(current) == 1) {
            if (current[0] == '\\') {
                if (reader.read(current) == 0) {
                    break;
                }
                previous = ' ';
                buffer.append(current[0]);
            } else if (current[0] == '(' && previous != ' ') {
                String funcName = buffer.toString();
                function = CompoundVariable.getNamedFunction(funcName.trim());
                if (function instanceof Function) {
                    ((Function) function).setParameters(parseParams(reader));
                    if (firstNonSpace(reader, '#') != '}') {
                        // set to start of string
                        reader.reset();
                        char[] cb = new char[100];
                        int nbRead = reader.read(cb);
                        throw new InvalidVariableException("Expected } after " + funcName + " function call in " + new String(cb, 0, nbRead));
                    }
                    if (function instanceof TestStateListener) {
                        StandardJMeterEngine.register((TestStateListener) function);
                    }
                    return function;
                } else {
                    // Function does not exist, so treat as per missing variable
                    buffer.append(current[0]);
                }
            } else if (current[0] == '}') {
                // variable, or function with no parameter list
                function = CompoundVariable.getNamedFunction(buffer.toString());
                if (function instanceof Function) {
                    // ensure that setParameters() is called.
                    ((Function) function).setParameters(new ArrayList<>());
                }
                buffer.setLength(0);
                return function;
            } else {
                buffer.append(current[0]);
                previous = current[0];
            }
        }
    } catch (IOException e) {
        log.error("Error parsing function: {}", buffer, e);
        return null;
    }
    log.warn("Probably an invalid function string: {}", buffer);
    return buffer.toString();
}
Also used : Function(org.apache.jmeter.functions.Function) InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) TestStateListener(org.apache.jmeter.testelement.TestStateListener) IOException(java.io.IOException)

Example 4 with InvalidVariableException

use of org.apache.jmeter.functions.InvalidVariableException in project jmeter by apache.

the class ProxyControlGui method startProxy.

private boolean startProxy() {
    ValueReplacer replacer = GuiPackage.getInstance().getReplacer();
    modifyTestElement(model);
    TreeNodeWrapper treeNodeWrapper = (TreeNodeWrapper) targetNodesModel.getSelectedItem();
    if (JMeterUtils.getResString("use_recording_controller").equals(treeNodeWrapper.getLabel())) {
        JMeterTreeNode targetNode = model.findTargetControllerNode();
        if (targetNode == null || !(targetNode.getTestElement() instanceof RecordingController)) {
            JOptionPane.showMessageDialog(this, // $NON-NLS-1$
            JMeterUtils.getResString("proxy_cl_wrong_target_cl"), // $NON-NLS-1$
            JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
    // Proxy can take some while to start up; show a waiting cursor
    Cursor cursor = getCursor();
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {
        replacer.replaceValues(model);
        model.startProxy();
        start.setEnabled(false);
        stop.setEnabled(true);
        restart.setEnabled(false);
        if (ProxyControl.isDynamicMode()) {
            String[] details = model.getCertificateDetails();
            StringBuilder sb = new StringBuilder();
            sb.append("<html>");
            // $NON-NLS-1$
            sb.append(JMeterUtils.getResString("proxy_daemon_msg_rootca_cert")).append("&nbsp;<b>").append(KeyToolUtils.ROOT_CACERT_CRT_PFX).append("</b>&nbsp;").append(JMeterUtils.getResString("proxy_daemon_msg_created_in_bin"));
            // $NON-NLS-1$
            sb.append("<br>").append(JMeterUtils.getResString("proxy_daemon_msg_install_as_in_doc"));
            sb.append("<br><b>").append(MessageFormat.format(JMeterUtils.getResString("proxy_daemon_msg_check_expiration"), // $NON-NLS-1$
            ProxyControl.CERT_VALIDITY)).append("</b><br>");
            sb.append("<br>").append(JMeterUtils.getResString("proxy_daemon_msg_check_details")).append(// $NON-NLS-1$
            "<ul>");
            for (String detail : details) {
                sb.append("<li>").append(detail).append("</li>");
            }
            sb.append("</ul>").append("</html>");
            // Make dialog disappear after 7 seconds
            JLabel messageLabel = new JLabel(sb.toString());
            Timer timer = new Timer(7000, evt -> {
                Window window = SwingUtilities.getWindowAncestor(messageLabel);
                // Window may be closed by user
                if (window != null) {
                    window.dispose();
                }
            });
            timer.setRepeats(false);
            timer.start();
            JOptionPane.showMessageDialog(this, messageLabel, // $NON-NLS-1$
            JMeterUtils.getResString("proxy_daemon_msg_rootca_cert") + SPACE + KeyToolUtils.ROOT_CACERT_CRT_PFX + SPACE + // $NON-NLS-1$
            JMeterUtils.getResString("proxy_daemon_msg_created_in_bin"), JOptionPane.INFORMATION_MESSAGE);
        }
        return true;
    } catch (InvalidVariableException e) {
        JOptionPane.showMessageDialog(this, // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.getResString("invalid_variables") + ": " + e.getMessage(), // $NON-NLS-1$
        JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
        return false;
    } catch (BindException e) {
        JOptionPane.showMessageDialog(this, // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.getResString("proxy_daemon_bind_error") + ": " + e.getMessage(), // $NON-NLS-1$
        JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
        return false;
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.getResString("proxy_daemon_error") + ": " + e.getMessage(), // $NON-NLS-1$
        JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
        return false;
    } finally {
        setCursor(cursor);
    }
}
Also used : Window(java.awt.Window) InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) TreeNodeWrapper(org.apache.jmeter.control.gui.TreeNodeWrapper) JLabel(javax.swing.JLabel) BindException(java.net.BindException) IOException(java.io.IOException) Cursor(java.awt.Cursor) Timer(javax.swing.Timer) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) ValueReplacer(org.apache.jmeter.engine.util.ValueReplacer) RecordingController(org.apache.jmeter.protocol.http.control.RecordingController)

Example 5 with InvalidVariableException

use of org.apache.jmeter.functions.InvalidVariableException in project jmeter by apache.

the class ProxyControl method replaceValues.

/**
 * Scan all test elements passed in for values matching the value of any of
 * the variables in any of the variable-holding elements in the collection.
 *
 * @param sampler   A TestElement to replace values on
 * @param configs   More TestElements to replace values on
 * @param variables Collection of Arguments to use to do the replacement, ordered
 *                  by ascending priority.
 */
private void replaceValues(TestElement sampler, TestElement[] configs, Collection<Arguments> variables) {
    // Build the replacer from all the variables in the collection:
    ValueReplacer replacer = new ValueReplacer();
    for (Arguments variable : variables) {
        final Map<String, String> map = variable.getArgumentsAsMap();
        // Drop any empty values (Bug 45199)
        map.values().removeIf(""::equals);
        replacer.addVariables(map);
    }
    try {
        boolean cachedRegexpMatch = regexMatch;
        replacer.reverseReplace(sampler, cachedRegexpMatch);
        for (TestElement config : configs) {
            if (config != null) {
                replacer.reverseReplace(config, cachedRegexpMatch);
            }
        }
    } catch (InvalidVariableException e) {
        log.warn("Invalid variables included for replacement into recorded sample", e);
    }
}
Also used : InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) Arguments(org.apache.jmeter.config.Arguments) ValueReplacer(org.apache.jmeter.engine.util.ValueReplacer) TestElement(org.apache.jmeter.testelement.TestElement) ConfigTestElement(org.apache.jmeter.config.ConfigTestElement) NonTestElement(org.apache.jmeter.testelement.NonTestElement)

Aggregations

InvalidVariableException (org.apache.jmeter.functions.InvalidVariableException)5 ValueReplacer (org.apache.jmeter.engine.util.ValueReplacer)3 TestElement (org.apache.jmeter.testelement.TestElement)3 IOException (java.io.IOException)2 Arguments (org.apache.jmeter.config.Arguments)2 ConfigTestElement (org.apache.jmeter.config.ConfigTestElement)2 JMeterTreeNode (org.apache.jmeter.gui.tree.JMeterTreeNode)2 NonTestElement (org.apache.jmeter.testelement.NonTestElement)2 TestPlan (org.apache.jmeter.testelement.TestPlan)2 Cursor (java.awt.Cursor)1 Window (java.awt.Window)1 BindException (java.net.BindException)1 JLabel (javax.swing.JLabel)1 Timer (javax.swing.Timer)1 TreeNodeWrapper (org.apache.jmeter.control.gui.TreeNodeWrapper)1 IllegalUserActionException (org.apache.jmeter.exceptions.IllegalUserActionException)1 Function (org.apache.jmeter.functions.Function)1 RecordingController (org.apache.jmeter.protocol.http.control.RecordingController)1 ResultCollector (org.apache.jmeter.reporters.ResultCollector)1 TestStateListener (org.apache.jmeter.testelement.TestStateListener)1