Search in sources :

Example 6 with JMeterError

use of org.apache.jorphan.util.JMeterError in project jmeter by apache.

the class BeanShellInterpreter method bshInvoke.

private Object bshInvoke(Method m, Object[] o, boolean shouldLog) throws JMeterException {
    Object r = null;
    final String errorString = "Error invoking bsh method: ";
    try {
        r = m.invoke(bshInstance, o);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        // Programming error
        final String message = errorString + m.getName();
        log.error(message);
        throw new JMeterError(message, e);
    } catch (InvocationTargetException e) {
        // Can occur at run-time
        // could be caused by the bsh Exceptions:
        // EvalError, ParseException or TargetError
        String message = errorString + m.getName();
        Throwable cause = e.getCause();
        if (cause != null) {
            message += "\t" + cause.getLocalizedMessage();
        }
        if (shouldLog) {
            log.error(message);
        }
        throw new JMeterException(message, e);
    }
    return r;
}
Also used : JMeterError(org.apache.jorphan.util.JMeterError) JMeterException(org.apache.jorphan.util.JMeterException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 7 with JMeterError

use of org.apache.jorphan.util.JMeterError in project jmeter by apache.

the class ResultCollector method loadExistingFile.

/**
     * Loads an existing sample data (JTL) file.
     * This can be one of:
     * <ul>
     *   <li>XStream format</li>
     *   <li>CSV format</li>
     * </ul>
     *
     */
public void loadExistingFile() {
    final Visualizer visualizer = getVisualizer();
    if (visualizer == null) {
        // No point reading the file if there's no visualiser
        return;
    }
    boolean parsedOK = false;
    String filename = getFilename();
    File file = new File(filename);
    if (file.exists()) {
        try (FileReader fr = new FileReader(file);
            BufferedReader dataReader = new BufferedReader(fr, 300)) {
            // Get the first line, and see if it is XML
            String line = dataReader.readLine();
            dataReader.close();
            if (line == null) {
                log.warn("{} is empty", filename);
            } else {
                if (!line.startsWith("<?xml ")) {
                    // No, must be CSV //$NON-NLS-1$
                    CSVSaveService.processSamples(filename, visualizer, this);
                    parsedOK = true;
                } else {
                    // We are processing XML
                    try (FileInputStream fis = new FileInputStream(file);
                        BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
                        // Assume XStream
                        SaveService.loadTestResults(bufferedInputStream, new ResultCollectorHelper(this, visualizer));
                        parsedOK = true;
                    } catch (Exception e) {
                        if (log.isWarnEnabled()) {
                            log.warn("Failed to load {} using XStream. Error was: {}", filename, e.toString());
                        }
                    }
                }
            }
        } catch (IOException | JMeterError | RuntimeException | OutOfMemoryError e) {
            // FIXME Why do we catch OOM ?
            log.warn("Problem reading JTL file: {}", file);
        } finally {
            if (!parsedOK) {
                GuiPackage.showErrorMessage("Error loading results file - see log file", "Result file loader");
            }
        }
    } else {
        GuiPackage.showErrorMessage("Error loading results file - could not open file", "Result file loader");
    }
}
Also used : IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) JMeterError(org.apache.jorphan.util.JMeterError) BufferedInputStream(java.io.BufferedInputStream) BufferedReader(java.io.BufferedReader) Visualizer(org.apache.jmeter.visualizers.Visualizer) FileReader(java.io.FileReader) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 8 with JMeterError

use of org.apache.jorphan.util.JMeterError in project jmeter by apache.

the class XPathExtractor method process.

/**
     * Do the job - extract value from (X)HTML response using XPath Query.
     * Return value as variable defined by REFNAME. Returns DEFAULT value
     * if not found.
     */
@Override
public void process() {
    JMeterContext context = getThreadContext();
    final SampleResult previousResult = context.getPreviousResult();
    if (previousResult == null) {
        return;
    }
    JMeterVariables vars = context.getVariables();
    String refName = getRefName();
    vars.put(refName, getDefaultValue());
    final String matchNR = concat(refName, REF_MATCH_NR);
    // number of previous matches
    int prevCount = 0;
    try {
        prevCount = Integer.parseInt(vars.get(matchNR));
    } catch (NumberFormatException e) {
    // ignored
    }
    // In case parse fails // $NON-NLS-1$
    vars.put(matchNR, "0");
    // In case parse fails // $NON-NLS-1$
    vars.remove(concat(refName, "1"));
    int matchNumber = getMatchNumber();
    List<String> matches = new ArrayList<>();
    try {
        if (isScopeVariable()) {
            String inputString = vars.get(getVariableName());
            if (inputString != null) {
                if (inputString.length() > 0) {
                    Document d = parseResponse(inputString);
                    getValuesForXPath(d, getXPathQuery(), matches, matchNumber);
                }
            } else {
                if (log.isWarnEnabled()) {
                    log.warn("No variable '{}' found to process by XPathExtractor '{}', skipping processing", getVariableName(), getName());
                }
            }
        } else {
            List<SampleResult> samples = getSampleList(previousResult);
            for (SampleResult res : samples) {
                Document d = parseResponse(res.getResponseDataAsString());
                getValuesForXPath(d, getXPathQuery(), matches, matchNumber);
            }
        }
        final int matchCount = matches.size();
        vars.put(matchNR, String.valueOf(matchCount));
        if (matchCount > 0) {
            String value = matches.get(0);
            if (value != null) {
                vars.put(refName, value);
            }
            for (int i = 0; i < matchCount; i++) {
                value = matches.get(i);
                if (value != null) {
                    vars.put(concat(refName, i + 1), matches.get(i));
                }
            }
        }
        // Just in case
        vars.remove(concat(refName, matchCount + 1));
        // Clear any other remaining variables
        for (int i = matchCount + 2; i <= prevCount; i++) {
            vars.remove(concat(refName, i));
        }
    } catch (IOException e) {
        // e.g. DTD not reachable
        log.error("IOException on ({})", getXPathQuery(), e);
        AssertionResult ass = new AssertionResult(getName());
        ass.setError(true);
        ass.setFailureMessage(new StringBuilder("IOException: ").append(e.getLocalizedMessage()).toString());
        previousResult.addAssertionResult(ass);
        previousResult.setSuccessful(false);
    } catch (ParserConfigurationException e) {
        // Should not happen
        final String errrorMessage = "ParserConfigurationException while processing (" + getXPathQuery() + ")";
        log.error(errrorMessage, e);
        throw new JMeterError(errrorMessage, e);
    } catch (SAXException e) {
        // Can happen for bad input document
        if (log.isWarnEnabled()) {
            log.warn("SAXException while processing ({}). {}", getXPathQuery(), e.getLocalizedMessage());
        }
        // Should this also fail the sample?
        addAssertionFailure(previousResult, e, false);
    } catch (TransformerException e) {
        // Can happen for incorrect XPath expression
        if (log.isWarnEnabled()) {
            log.warn("TransformerException while processing ({}). {}", getXPathQuery(), e.getLocalizedMessage());
        }
        addAssertionFailure(previousResult, e, false);
    } catch (TidyException e) {
        // Will already have been logged by XPathUtil
        // fail the sample
        addAssertionFailure(previousResult, e, true);
    }
}
Also used : AssertionResult(org.apache.jmeter.assertions.AssertionResult) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) TidyException(org.apache.jmeter.util.TidyException) SAXException(org.xml.sax.SAXException) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterError(org.apache.jorphan.util.JMeterError) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 9 with JMeterError

use of org.apache.jorphan.util.JMeterError in project jmeter by apache.

the class TestFunctor method testClass.

// Check how Class definition behaves
@Test
public void testClass() throws Exception {
    Test1 t1 = new Test1("t1");
    Test1 t1a = new Test1a("t1a");
    Test2 t2 = new Test2("t2");
    Functor f1 = new Functor(HasName.class, "getName");
    assertEquals("t1", f1.invoke(t1));
    assertEquals("1a:t1a.", f1.invoke(t1a));
    assertEquals("t2", f1.invoke(t2));
    try {
        f1.invoke();
        fail("Should have failed");
    } catch (IllegalStateException ok) {
    }
    Functor f2 = new Functor(HasString.class, "getString");
    assertEquals("xyz", f2.invoke(t2, new String[] { "xyz" }));
    try {
        f2.invoke(t1, new String[] { "xyz" });
        fail("Should have failed");
    } catch (JMeterError ok) {
    }
    Functor f3 = new Functor(t2, "getString");
    assertEquals("xyz", f3.invoke(t2, new Object[] { "xyz" }));
    Properties p = new Properties();
    p.put("Name", "Value");
    Functor fk = new Functor(Map.Entry.class, "getKey");
    Functor fv = new Functor(Map.Entry.class, "getValue");
    Object o = p.entrySet().iterator().next();
    assertEquals("Name", fk.invoke(o));
    assertEquals("Value", fv.invoke(o));
}
Also used : JMeterError(org.apache.jorphan.util.JMeterError) Properties(java.util.Properties) Map(java.util.Map) Test(org.junit.Test)

Example 10 with JMeterError

use of org.apache.jorphan.util.JMeterError in project jmeter by apache.

the class JMeterThread method run.

@Override
public void run() {
    // threadContext is not thread-safe, so keep within thread
    JMeterContext threadContext = JMeterContextService.getContext();
    LoopIterationListener iterationListener = null;
    try {
        iterationListener = initRun(threadContext);
        while (running) {
            Sampler sam = threadGroupLoopController.next();
            while (running && sam != null) {
                processSampler(sam, null, threadContext);
                threadContext.cleanAfterSample();
                // - or the last sample failed AND the onErrorStartNextLoop option is enabled
                if (threadContext.isRestartNextLoop() || (onErrorStartNextLoop && !TRUE.equals(threadContext.getVariables().get(LAST_SAMPLE_OK)))) {
                    if (log.isDebugEnabled() && onErrorStartNextLoop && !threadContext.isRestartNextLoop()) {
                        log.debug("StartNextLoop option is on, Last sample failed, starting next loop");
                    }
                    triggerEndOfLoopOnParentControllers(sam, threadContext);
                    sam = null;
                    threadContext.getVariables().put(LAST_SAMPLE_OK, TRUE);
                    threadContext.setRestartNextLoop(false);
                } else {
                    sam = threadGroupLoopController.next();
                }
            }
            if (threadGroupLoopController.isDone()) {
                running = false;
                log.info("Thread is done: {}", threadName);
            }
        }
    }// Might be found by controller.next()
     catch (JMeterStopTestException e) {
        // NOSONAR
        if (log.isInfoEnabled()) {
            log.info("Stopping Test: {}", e.toString());
        }
        shutdownTest();
    } catch (JMeterStopTestNowException e) {
        // NOSONAR
        if (log.isInfoEnabled()) {
            log.info("Stopping Test Now: {}", e.toString());
        }
        stopTestNow();
    } catch (JMeterStopThreadException e) {
        // NOSONAR
        if (log.isInfoEnabled()) {
            log.info("Stop Thread seen for thread {}, reason: {}", getThreadName(), e.toString());
        }
    } catch (Exception | JMeterError e) {
        log.error("Test failed!", e);
    } catch (ThreadDeath e) {
        // Must not ignore this one
        throw e;
    } finally {
        // prevent any further interrupts
        currentSampler = null;
        try {
            // make sure current interrupt is finished, prevent another starting yet
            interruptLock.lock();
            threadContext.clear();
            log.info("Thread finished: {}", threadName);
            threadFinished(iterationListener);
            // Tell the monitor we are done
            monitor.threadFinished(this);
            // Remove the ThreadLocal entry
            JMeterContextService.removeContext();
        } finally {
            // Allow any pending interrupt to complete (OK because currentSampler == null)
            interruptLock.unlock();
        }
    }
}
Also used : JMeterStopTestNowException(org.apache.jorphan.util.JMeterStopTestNowException) JMeterStopThreadException(org.apache.jorphan.util.JMeterStopThreadException) JMeterStopTestException(org.apache.jorphan.util.JMeterStopTestException) LoopIterationListener(org.apache.jmeter.engine.event.LoopIterationListener) JMeterError(org.apache.jorphan.util.JMeterError) TransactionSampler(org.apache.jmeter.control.TransactionSampler) Sampler(org.apache.jmeter.samplers.Sampler) JMeterStopTestException(org.apache.jorphan.util.JMeterStopTestException) JMeterStopThreadException(org.apache.jorphan.util.JMeterStopThreadException) JMeterStopTestNowException(org.apache.jorphan.util.JMeterStopTestNowException)

Aggregations

JMeterError (org.apache.jorphan.util.JMeterError)11 IOException (java.io.IOException)4 FileInputStream (java.io.FileInputStream)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Map (java.util.Map)2 Properties (java.util.Properties)2 AssertionResult (org.apache.jmeter.assertions.AssertionResult)2 SampleResult (org.apache.jmeter.samplers.SampleResult)2 JMeterStopTestException (org.apache.jorphan.util.JMeterStopTestException)2 JMeterStopTestNowException (org.apache.jorphan.util.JMeterStopTestNowException)2 JMeterStopThreadException (org.apache.jorphan.util.JMeterStopThreadException)2 Component (java.awt.Component)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedReader (java.io.BufferedReader)1 EOFException (java.io.EOFException)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 FileReader (java.io.FileReader)1 InputStream (java.io.InputStream)1 ObjectInputStream (java.io.ObjectInputStream)1