Move to Java 17 (migrate source code from Java 8) (#6462)
Validate Gradle Wrapper / Validation (push) Has been cancelled Details
CI / Matrix Preparation (push) Has been cancelled Details
CI / Error Prone (JDK 17) (push) Has been cancelled Details
Release Drafter / Update Release Draft (push) Has been cancelled Details
CI / ${{ matrix.name }} (push) Has been cancelled Details

* Prepare to use Java 17 as minimal version

* See #6219 Pattern Matching for instanceof uses (Java 14/16)

* See #6219 - Implicit Typing with var (Java 10)

* See #6219 - Using Switch Expressions / yield Keyword (Java 14)

* See #6219 - Using Text Blocks (Java 15)

* See #6219 - some tunning / formating style

* See #6219 - tunning code

* See #6219 - Update Java argline params / remove java 8 / 9 args/comments

* See #6219 - formating code

* Remove not standard options for Java 17

* See #6219 - refactor CompOper to an enum

* See #6219 - fix unnecessary yield usage in the switch expression

* See #6219 - Optimize the code, fix formatting issue
This commit is contained in:
Milamber 2025-07-07 09:43:25 +01:00 committed by GitHub
parent 77675e0b8e
commit 83e211fed7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 495 additions and 509 deletions

View File

@ -115,18 +115,19 @@ if [ -z "$JAVA_HOME" ]; then
JAVA_HOME="$JRE_HOME"
fi
#--add-opens if JAVA 9
JAVA9_OPTS=
# Module access for modern Java versions (required for JMeter components)
JAVA_OPTS="--add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.swing=ALL-UNNAMED --add-opens java.desktop/javax.swing.text.html=ALL-UNNAMED --add-opens java.desktop/java.awt=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/sun.awt.X11=ALL-UNNAMED --add-opens=java.desktop/sun.awt.shell=ALL-UNNAMED"
# Minimal version to run JMeter
MINIMAL_VERSION=8
MINIMAL_VERSION=17
# Check if version is from OpenJDK or Oracle Hotspot JVM prior to 9 containing 1.${version}.x
# Check if version meets the minimal requirement
CURRENT_VERSION=`"${JAVA_HOME}/bin/java" -version 2>&1 | awk -F'"' '/version/ {gsub("^1[.]", "", $2); gsub("[^0-9].*$", "", $2); print $2}'`
# Check if Java is present and the minimal version requirement
if [ "$CURRENT_VERSION" -gt "$MINIMAL_VERSION" ]; then
JAVA9_OPTS="--add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.swing=ALL-UNNAMED --add-opens java.desktop/javax.swing.text.html=ALL-UNNAMED --add-opens java.desktop/java.awt=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/sun.awt.X11=ALL-UNNAMED --add-opens=java.desktop/sun.awt.shell=ALL-UNNAMED"
# Check if Java is present and meets the minimal version requirement
if [ "$CURRENT_VERSION" -lt "$MINIMAL_VERSION" ]; then
echo "ERROR: Java version $CURRENT_VERSION is too low. JMeter requires Java $MINIMAL_VERSION or higher."
exit 1
fi
: "${JMETER_OPTS:=""}"
@ -169,15 +170,19 @@ esac
# Default to en_EN
: "${JMETER_LANGUAGE:="-Duser.language=en -Duser.region=EN"}"
# Uncomment this to generate GC verbose file with Java prior to 9
# VERBOSE_GC="-verbose:gc -Xloggc:gc_jmeter_%p.log -XX:+PrintGCDetails -XX:+PrintGCCause -XX:+PrintTenuringDistribution -XX:+PrintHeapAtGC -XX:+PrintGCApplicationConcurrentTime -XX:+PrintAdaptiveSizePolicy -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps"
# Legacy GC verbose options removed (Java 8/9 support discontinued)
# Uncomment this to generate GC verbose file with Java 9 and above
# VERBOSE_GC="-Xlog:gc*,gc+age=trace,gc+heap=debug:file=gc_jmeter_%p.log"
# Optimized GC logging for Java 17 with structured output and performance analysis
# Uncomment to enable comprehensive GC logging with rotation and detailed metrics
# VERBOSE_GC="-Xlog:gc,gc+heap,gc+regions,gc+refine,gc+phases:gc_jmeter_%p_%t.log:time,level,tags:filecount=5,filesize=50M"
# Alternative: Minimal GC logging for production (uncomment if needed)
# VERBOSE_GC="-Xlog:gc:gc_jmeter_%p.log:time"
# Docker support for Java 17+
# Modern container memory detection is automatic in Java 17+
# RUN_IN_DOCKER="-XX:+UseContainerSupport"
# Uncomment this if you run JMeter in DOCKER (need Java SE 8u131 or JDK 9)
# see https://blogs.oracle.com/java-platform-group/java-se-support-for-docker-cpu-and-memory-limits
# RUN_IN_DOCKER="-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap"
# Finally, some tracing to help in case things go astray:
# You may want to add those settings:
@ -191,7 +196,7 @@ SYSTEM_PROPS="-Djava.security.egd=file:/dev/urandom"
SERVER="-server"
if [ -z "${JMETER_COMPLETE_ARGS}" ]; then
ARGS="$JAVA9_OPTS $SERVER $DUMP $HEAP $VERBOSE_GC $GC_ALGO $SYSTEM_PROPS $JMETER_LANGUAGE $RUN_IN_DOCKER"
ARGS="$JAVA_OPTS $SERVER $DUMP $HEAP $VERBOSE_GC $GC_ALGO $SYSTEM_PROPS $JMETER_LANGUAGE $RUN_IN_DOCKER"
else
ARGS=""
fi

View File

@ -78,12 +78,19 @@ if not defined JMETER_LANGUAGE (
)
rem Minimal version to run JMeter
set MINIMAL_VERSION=1.8.0
set MINIMAL_VERSION=17.0.0
rem --add-opens if JAVA 9
set JAVA9_OPTS=
rem Optimized GC logging for Java 17 with structured output and performance analysis
rem Uncomment to enable comprehensive GC logging with rotation and detailed metrics
rem set VERBOSE_GC=-Xlog:gc,gc+heap,gc+regions,gc+refine,gc+phases:gc_jmeter_%%p_%%t.log:time,level,tags:filecount=5,filesize=50M
rem Alternative: Minimal GC logging for production (uncomment if needed)
rem set VERBOSE_GC=-Xlog:gc:gc_jmeter_%%p.log:time
rem Module access for modern Java versions (required for JMeter components)
set JAVA_OPTS=--add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.swing=ALL-UNNAMED --add-opens java.desktop/javax.swing.text.html=ALL-UNNAMED --add-opens java.desktop/java.awt=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/sun.awt.shell=ALL-UNNAMED
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
rem @echo Debug Output: %%g
@ -95,36 +102,24 @@ if not defined JAVAVER (
goto pause
)
rem Check if version is from OpenJDK or Oracle Hotspot JVM prior to 9 containing 1.${version}.x
rem JAVAVER will be equal to "9.0.4" (quotes are part of the value) for Oracle Java 9
rem JAVAVER will be equal to "1.8.0_161" (quotes are part of the value) for Oracle Java 8
rem so we extract 2 chars starting from index 1
IF "%JAVAVER:~1,2%"=="1." (
set JAVAVER=%JAVAVER:"=%
for /f "delims=. tokens=1-3" %%v in ("%JAVAVER%") do (
set current_minor=%%w
)
) else (
rem Java 9 at least
set current_minor=9
set JAVA9_OPTS=--add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.swing=ALL-UNNAMED --add-opens java.desktop/javax.swing.text.html=ALL-UNNAMED --add-opens java.desktop/java.awt=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/sun.awt.shell=ALL-UNNAMED
rem Extract major version number from Java version string
for /f "delims=. tokens=1" %%v in ("%JAVAVER:~1,-1%") do (
set current_major=%%v
)
for /f "delims=. tokens=1-3" %%v in ("%MINIMAL_VERSION%") do (
set minimal_minor=%%w
rem Extract minimal major version
for /f "delims=. tokens=1" %%v in ("%MINIMAL_VERSION%") do (
set minimal_major=%%v
)
if not defined current_minor (
if not defined current_major (
@echo Not able to find Java executable or version. Please check your Java installation.
set ERRORLEVEL=2
goto pause
)
rem @echo Debug: CURRENT=%current_minor% - MINIMAL=%minimal_minor%
if %current_minor% LSS %minimal_minor% (
@echo Error: Java version -- %JAVAVER% -- is too low to run JMeter. Needs a Java version greater than or equal to %MINIMAL_VERSION%
if %current_major% LSS %minimal_major% (
@echo Error: Java version -- %JAVAVER% -- is too low to run JMeter. Needs Java %MINIMAL_VERSION% or higher.
set ERRORLEVEL=3
goto pause
)
@ -151,13 +146,7 @@ if not defined HEAP (
set HEAP=-Xms1g -Xmx1g -XX:MaxMetaspaceSize=256m
)
rem Uncomment this to generate GC verbose file with Java prior to 9
rem set VERBOSE_GC=-verbose:gc -Xloggc:gc_jmeter_%%p.log -XX:+PrintGCDetails -XX:+PrintGCCause -XX:+PrintTenuringDistribution -XX:+PrintHeapAtGC -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintAdaptiveSizePolicy
rem Uncomment this to generate GC verbose file with Java 9 and above
rem set VERBOSE_GC=-Xlog:gc*,gc+age=trace,gc+heap=debug:file=gc_jmeter_%%p.log
rem You may want to add those settings
rem -XX:+ParallelRefProcEnabled -XX:+PerfDisableSharedMem
rem Legacy GC verbose options removed (Java 8/9 support discontinued)
if not defined GC_ALGO (
set GC_ALGO=-XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:G1ReservePercent=20
)
@ -167,9 +156,9 @@ set SYSTEM_PROPS=-Djava.security.egd=file:/dev/urandom
rem Always dump on OOM (does not cost anything unless triggered)
set DUMP=-XX:+HeapDumpOnOutOfMemoryError
rem Uncomment this if you run JMeter in DOCKER (need Java SE 8u131 or JDK 9)
rem see https://blogs.oracle.com/java-platform-group/java-se-support-for-docker-cpu-and-memory-limits
rem set RUN_IN_DOCKER=-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap
rem Docker support for Java 17+
rem Modern container memory detection is automatic in Java 17+
rem set RUN_IN_DOCKER=-XX:+UseContainerSupport
rem Additional settings that might help improve GUI performance on some platforms
rem See: http://www.oracle.com/technetwork/java/perf-graphics-135933.html
@ -188,7 +177,7 @@ if not defined DDRAW (
rem Collect the settings defined above
if not defined JMETER_COMPLETE_ARGS (
set ARGS=%JAVA9_OPTS% %DUMP% %HEAP% %VERBOSE_GC% %GC_ALGO% %DDRAW% %SYSTEM_PROPS% %JMETER_LANGUAGE% %RUN_IN_DOCKER%
set ARGS=%JAVA_OPTS% %DUMP% %HEAP% %VERBOSE_GC% %GC_ALGO% %DDRAW% %SYSTEM_PROPS% %JMETER_LANGUAGE% %RUN_IN_DOCKER%
) else (
set ARGS=
)

View File

@ -90,14 +90,17 @@ fi
JAVA9_OPTS=
# Minimal version to run JMeter
MINIMAL_VERSION=8
MINIMAL_VERSION=17
# Check if version is from OpenJDK or Oracle Hotspot JVM prior to 9 containing 1.${version}.x
CURRENT_VERSION=`"${JAVA_HOME}/bin/java" -version 2>&1 | awk -F'"' '/version/ {gsub("^1[.]", "", $2); gsub("[^0-9].*$", "", $2); print $2}'`
# Check if Java is present and the minimal version requirement
if [ "$CURRENT_VERSION" -gt "$MINIMAL_VERSION" ]; then
if [ "$CURRENT_VERSION" -ge "$MINIMAL_VERSION" ]; then
JAVA9_OPTS="--add-opens java.desktop/sun.awt=ALL-UNNAMED --add-opens java.desktop/sun.swing=ALL-UNNAMED --add-opens java.desktop/javax.swing.text.html=ALL-UNNAMED --add-opens java.desktop/java.awt=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens=java.desktop/sun.awt.X11=ALL-UNNAMED --add-opens=java.desktop/sun.awt.shell=ALL-UNNAMED"
else
echo "JMeter requires Java $MINIMAL_VERSION or later. Current Java version is $CURRENT_VERSION"
exit 1
fi
# Don't add additional arguments to the JVM start, except those needed for Java 9

View File

@ -121,18 +121,14 @@ tasks.configureEach<Javadoc> {
docTitle = "Apache JMeter ${project.name} API"
windowTitle = "Apache JMeter ${project.name} API"
header = "<b>Apache JMeter</b>"
addStringOption("source", "8")
addStringOption("source", "17")
addStringOption("Xmaxwarns", "10")
addBooleanOption("Xdoclint:all,-missing", true)
val lastEditYear: String by rootProject.extra
bottom =
"Copyright &copy; 1998-$lastEditYear Apache Software Foundation. All Rights Reserved."
if (buildParameters.buildJdkVersion > 8) {
addBooleanOption("html5", true)
links("https://docs.oracle.com/en/java/javase/11/docs/api/")
} else {
links("https://docs.oracle.com/javase/8/docs/api/")
}
links("https://docs.oracle.com/en/java/javase/17/docs/api/")
}
}

View File

@ -35,17 +35,86 @@ public class SizeAssertion extends AbstractScopedAssertion implements Serializab
private static final long serialVersionUID = 241L;
// Static int to signify the type of logical comparator to assert
/**
* Comparison operators for size assertions
*/
public enum ComparisonOperator {
EQUAL(1, "size_assertion_comparator_error_equal"),
NOTEQUAL(2, "size_assertion_comparator_error_notequal"),
GREATERTHAN(3, "size_assertion_comparator_error_greater"),
LESSTHAN(4, "size_assertion_comparator_error_less"),
GREATERTHANEQUAL(5, "size_assertion_comparator_error_greaterequal"),
LESSTHANEQUAL(6, "size_assertion_comparator_error_lessequal");
private static final ComparisonOperator[] VALUES = values();
private final int value;
private final String errorMessageKey;
ComparisonOperator(int value, String errorMessageKey) {
this.value = value;
this.errorMessageKey = errorMessageKey;
}
public int getValue() {
return value;
}
public String getErrorMessageKey() {
return errorMessageKey;
}
public static ComparisonOperator fromValue(int value) {
for (ComparisonOperator op : VALUES) {
if (op.value == value) {
return op;
}
}
return null;
}
public boolean evaluate(long actual, long expected) {
switch (this) {
case EQUAL:
return actual == expected;
case NOTEQUAL:
return actual != expected;
case GREATERTHAN:
return actual > expected;
case LESSTHAN:
return actual < expected;
case GREATERTHANEQUAL:
return actual >= expected;
case LESSTHANEQUAL:
return actual <= expected;
}
throw new IllegalStateException("Unexpected value: " + this);
}
}
// Backward compatibility constants - deprecated
/** @deprecated Use {@link ComparisonOperator#EQUAL} instead */
@Deprecated
public static final int EQUAL = 1;
/** @deprecated Use {@link ComparisonOperator#NOTEQUAL} instead */
@Deprecated
public static final int NOTEQUAL = 2;
/** @deprecated Use {@link ComparisonOperator#GREATERTHAN} instead */
@Deprecated
public static final int GREATERTHAN = 3;
/** @deprecated Use {@link ComparisonOperator#LESSTHAN} instead */
@Deprecated
public static final int LESSTHAN = 4;
/** @deprecated Use {@link ComparisonOperator#GREATERTHANEQUAL} instead */
@Deprecated
public static final int GREATERTHANEQUAL = 5;
/** @deprecated Use {@link ComparisonOperator#LESSTHANEQUAL} instead */
@Deprecated
public static final int LESSTHANEQUAL = 6;
/** Key for storing assertion-information in the jmx-file. */
@ -175,41 +244,17 @@ public class SizeAssertion extends AbstractScopedAssertion implements Serializab
*
*/
private String compareSize(long resultSize) {
String comparatorErrorMessage;
long allowedSize = Long.parseLong(getAllowedSize());
boolean result;
int comp = getCompOper();
switch (comp) {
case EQUAL:
result = resultSize == allowedSize;
comparatorErrorMessage = JMeterUtils.getResString("size_assertion_comparator_error_equal"); //$NON-NLS-1$
break;
case NOTEQUAL:
result = resultSize != allowedSize;
comparatorErrorMessage = JMeterUtils.getResString("size_assertion_comparator_error_notequal"); //$NON-NLS-1$
break;
case GREATERTHAN:
result = resultSize > allowedSize;
comparatorErrorMessage = JMeterUtils.getResString("size_assertion_comparator_error_greater"); //$NON-NLS-1$
break;
case LESSTHAN:
result = resultSize < allowedSize;
comparatorErrorMessage = JMeterUtils.getResString("size_assertion_comparator_error_less"); //$NON-NLS-1$
break;
case GREATERTHANEQUAL:
result = resultSize >= allowedSize;
comparatorErrorMessage = JMeterUtils.getResString("size_assertion_comparator_error_greaterequal"); //$NON-NLS-1$
break;
case LESSTHANEQUAL:
result = resultSize <= allowedSize;
comparatorErrorMessage = JMeterUtils.getResString("size_assertion_comparator_error_lessequal"); //$NON-NLS-1$
break;
default:
result = false;
comparatorErrorMessage = "ERROR - invalid condition";
break;
ComparisonOperator operator = ComparisonOperator.fromValue(getCompOper());
if (operator == null) {
return "ERROR - invalid condition";
}
if (operator.evaluate(resultSize, allowedSize)) {
return "";
} else {
return JMeterUtils.getResString(operator.getErrorMessageKey());
}
return result ? "" : comparatorErrorMessage;
}
private void setTestField(String testField) {

View File

@ -135,7 +135,7 @@ public class SizeAssertionGui extends AbstractAssertionGui implements ActionList
lessthanButton.setSelected(false);
greaterthanequalButton.setSelected(false);
lessthanequalButton.setSelected(false);
execState = SizeAssertion.EQUAL;
execState = SizeAssertion.ComparisonOperator.EQUAL.getValue();
}
@Override
@ -164,32 +164,32 @@ public class SizeAssertionGui extends AbstractAssertionGui implements ActionList
* <p>
* Allowed states are
* <ul>
* <li>{@link SizeAssertion#EQUAL}</li>
* <li>{@link SizeAssertion#NOTEQUAL}</li>
* <li>{@link SizeAssertion#GREATERTHAN}</li>
* <li>{@link SizeAssertion#LESSTHAN}</li>
* <li>{@link SizeAssertion#GREATERTHANEQUAL}</li>
* <li>{@link SizeAssertion#LESSTHANEQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#EQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#NOTEQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#GREATERTHAN}</li>
* <li>{@link SizeAssertion.ComparisonOperator#LESSTHAN}</li>
* <li>{@link SizeAssertion.ComparisonOperator#GREATERTHANEQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#LESSTHANEQUAL}</li>
* </ul>
* @param state One of the allowed states
*/
public void setState(int state) {
if (state == SizeAssertion.EQUAL) {
if (state == SizeAssertion.ComparisonOperator.EQUAL.getValue()) {
equalButton.setSelected(true);
execState = state;
} else if (state == SizeAssertion.NOTEQUAL) {
} else if (state == SizeAssertion.ComparisonOperator.NOTEQUAL.getValue()) {
notequalButton.setSelected(true);
execState = state;
} else if (state == SizeAssertion.GREATERTHAN) {
} else if (state == SizeAssertion.ComparisonOperator.GREATERTHAN.getValue()) {
greaterthanButton.setSelected(true);
execState = state;
} else if (state == SizeAssertion.LESSTHAN) {
} else if (state == SizeAssertion.ComparisonOperator.LESSTHAN.getValue()) {
lessthanButton.setSelected(true);
execState = state;
} else if (state == SizeAssertion.GREATERTHANEQUAL) {
} else if (state == SizeAssertion.ComparisonOperator.GREATERTHANEQUAL.getValue()) {
greaterthanequalButton.setSelected(true);
execState = state;
} else if (state == SizeAssertion.LESSTHANEQUAL) {
} else if (state == SizeAssertion.ComparisonOperator.LESSTHANEQUAL.getValue()) {
lessthanequalButton.setSelected(true);
execState = state;
}
@ -200,12 +200,12 @@ public class SizeAssertionGui extends AbstractAssertionGui implements ActionList
* <p>
* Possible states are
* <ul>
* <li>{@link SizeAssertion#EQUAL}</li>
* <li>{@link SizeAssertion#NOTEQUAL}</li>
* <li>{@link SizeAssertion#GREATERTHAN}</li>
* <li>{@link SizeAssertion#LESSTHAN}</li>
* <li>{@link SizeAssertion#GREATERTHANEQUAL}</li>
* <li>{@link SizeAssertion#LESSTHANEQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#EQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#NOTEQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#GREATERTHAN}</li>
* <li>{@link SizeAssertion.ComparisonOperator#LESSTHAN}</li>
* <li>{@link SizeAssertion.ComparisonOperator#GREATERTHANEQUAL}</li>
* <li>{@link SizeAssertion.ComparisonOperator#LESSTHANEQUAL}</li>
* </ul>
* @return The current state of the radio Button
*/
@ -273,12 +273,12 @@ public class SizeAssertionGui extends AbstractAssertionGui implements ActionList
private Box createComparatorButtonPanel() {
ButtonGroup group = new ButtonGroup();
equalButton = createComparatorButton("=", SizeAssertion.EQUAL, group); //$NON-NLS-1$
notequalButton = createComparatorButton("!=", SizeAssertion.NOTEQUAL, group); //$NON-NLS-1$
greaterthanButton = createComparatorButton(">", SizeAssertion.GREATERTHAN, group); //$NON-NLS-1$
lessthanButton = createComparatorButton("<", SizeAssertion.LESSTHAN, group); //$NON-NLS-1$
greaterthanequalButton = createComparatorButton(">=", SizeAssertion.GREATERTHANEQUAL, group); //$NON-NLS-1$
lessthanequalButton = createComparatorButton("<=", SizeAssertion.LESSTHANEQUAL, group); //$NON-NLS-1$
equalButton = createComparatorButton("=", SizeAssertion.ComparisonOperator.EQUAL.getValue(), group); //$NON-NLS-1$
notequalButton = createComparatorButton("!=", SizeAssertion.ComparisonOperator.NOTEQUAL.getValue(), group); //$NON-NLS-1$
greaterthanButton = createComparatorButton(">", SizeAssertion.ComparisonOperator.GREATERTHAN.getValue(), group); //$NON-NLS-1$
lessthanButton = createComparatorButton("<", SizeAssertion.ComparisonOperator.LESSTHAN.getValue(), group); //$NON-NLS-1$
greaterthanequalButton = createComparatorButton(">=", SizeAssertion.ComparisonOperator.GREATERTHANEQUAL.getValue(), group); //$NON-NLS-1$
lessthanequalButton = createComparatorButton("<=", SizeAssertion.ComparisonOperator.LESSTHANEQUAL.getValue(), group); //$NON-NLS-1$
equalButton.setSelected(true);
execState = Integer.parseInt(equalButton.getActionCommand());

View File

@ -222,20 +222,12 @@ public class CSVDataSet extends ConfigTestElement
private void setAlias(final JMeterContext context, String alias) {
String mode = getShareMode();
int modeInt = CSVDataSetBeanInfo.getShareModeAsInt(mode);
switch(modeInt){
case CSVDataSetBeanInfo.SHARE_ALL:
this.alias = alias;
break;
case CSVDataSetBeanInfo.SHARE_GROUP:
this.alias = alias + "@" + System.identityHashCode(context.getThreadGroup());
break;
case CSVDataSetBeanInfo.SHARE_THREAD:
this.alias = alias + "@" + System.identityHashCode(context.getThread());
break;
default:
this.alias = alias + "@" + mode; // user-specified key
break;
}
this.alias = switch(modeInt){
case CSVDataSetBeanInfo.SHARE_ALL -> alias;
case CSVDataSetBeanInfo.SHARE_GROUP -> alias + "@" + System.identityHashCode(context.getThreadGroup());
case CSVDataSetBeanInfo.SHARE_THREAD -> alias + "@" + System.identityHashCode(context.getThread());
default -> alias + "@" + mode; // user-specified key
};
}
/**

View File

@ -157,12 +157,12 @@ public class JSONPostProcessor
if (matchNumber < 0) {
// Extract all
int index = 1;
StringBuilder concat =
var concat =
new StringBuilder(getComputeConcatenation()
? extractedValues.size() * 20
: 1);
for (Object extractedObject : extractedValues) {
String extractedString = Objects.toString(extractedObject, defaultValue);
var extractedString = Objects.toString(extractedObject, defaultValue);
vars.put(currentRefName + "_" + index,
extractedString); //$NON-NLS-1$
if (getComputeConcatenation()) {

View File

@ -114,26 +114,13 @@ public class TestActionGui extends AbstractSamplerGui { // NOSONAR Ignore hierar
}
action = ta.getAction();
switch (action) {
case TestAction.PAUSE:
pauseButton.setSelected(true);
break;
case TestAction.STOP_NOW:
stopNowButton.setSelected(true);
break;
case TestAction.STOP:
stopButton.setSelected(true);
break;
case TestAction.RESTART_NEXT_LOOP:
restartNextThreadLoopButton.setSelected(true);
break;
case TestAction.START_NEXT_ITERATION_CURRENT_LOOP:
startNextIterationOfCurrentLoopButton.setSelected(true);
break;
case TestAction.BREAK_CURRENT_LOOP:
breakLoopButton.setSelected(true);
break;
default:
break;
case TestAction.PAUSE -> pauseButton.setSelected(true);
case TestAction.STOP_NOW -> stopNowButton.setSelected(true);
case TestAction.STOP -> stopButton.setSelected(true);
case TestAction.RESTART_NEXT_LOOP -> restartNextThreadLoopButton.setSelected(true);
case TestAction.START_NEXT_ITERATION_CURRENT_LOOP -> startNextIterationOfCurrentLoopButton.setSelected(true);
case TestAction.BREAK_CURRENT_LOOP -> breakLoopButton.setSelected(true);
default -> { /* no action needed */ }
}
durationField.setText(ta.getDurationAsString());

View File

@ -546,12 +546,14 @@ implements ActionListener, TreeSelectionListener, Clearable, ItemListener {
// they are ready to wait.
int len = res.getResponseDataAsString().length();
if (MAX_DISPLAY_SIZE > 0 && len > MAX_DISPLAY_SIZE) {
StringBuilder builder = new StringBuilder(MAX_DISPLAY_SIZE + 100);
builder.append(JMeterUtils.getResString("view_results_response_too_large_message")) //$NON-NLS-1$
.append(len).append(" > Max: ").append(MAX_DISPLAY_SIZE)
.append(", ").append(JMeterUtils.getResString("view_results_response_partial_message")) // $NON-NLS-1$
.append("\n").append(res.getResponseDataAsString(), 0, MAX_DISPLAY_SIZE).append("\n...");
response = builder.toString();
response = """
%s%d > Max: %d, %s
%s
...""".formatted(
JMeterUtils.getResString("view_results_response_too_large_message"), //$NON-NLS-1$
len, MAX_DISPLAY_SIZE,
JMeterUtils.getResString("view_results_response_partial_message"), // $NON-NLS-1$
res.getResponseDataAsString().substring(0, MAX_DISPLAY_SIZE));
} else {
response = res.getResponseDataAsString();
}

View File

@ -178,15 +178,15 @@ public class SamplerMetric {
*/
public synchronized void resetForTimeInterval() {
switch (globalWindowMode) {
case FIXED:
case FIXED -> {
// We don't clear responsesStats nor usersStats as it will slide as per my understanding of
// http://commons.apache.org/proper/commons-math/userguide/stat.html
break;
case TIMED:
}
case TIMED -> {
for (DescriptiveStatistics stat : windowedStats) {
stat.clear();
}
break;
}
}
errors.clear();
successes = 0;

View File

@ -55,7 +55,7 @@ public class SizeAssertionTest extends JMeterTestCase {
@Test
public void testSizeAssertionEquals() throws Exception {
assertion.setCompOper(SizeAssertion.EQUAL);
assertion.setCompOper(SizeAssertion.ComparisonOperator.EQUAL.getValue());
assertion.setAllowedSize(0);
result = assertion.getResult(sample1);
assertFailed();
@ -73,7 +73,7 @@ public class SizeAssertionTest extends JMeterTestCase {
@Test
public void testSizeAssertionNotEquals() throws Exception {
assertion.setCompOper(SizeAssertion.NOTEQUAL);
assertion.setCompOper(SizeAssertion.ComparisonOperator.NOTEQUAL.getValue());
assertion.setAllowedSize(0);
result = assertion.getResult(sample1);
assertPassed();
@ -91,7 +91,7 @@ public class SizeAssertionTest extends JMeterTestCase {
@Test
public void testSizeAssertionGreaterThan() throws Exception {
assertion.setCompOper(SizeAssertion.GREATERTHAN);
assertion.setCompOper(SizeAssertion.ComparisonOperator.GREATERTHAN.getValue());
assertion.setAllowedSize(0);
result = assertion.getResult(sample1);
assertPassed();
@ -109,7 +109,7 @@ public class SizeAssertionTest extends JMeterTestCase {
@Test
public void testSizeAssertionGreaterThanEqual() throws Exception {
assertion.setCompOper(SizeAssertion.GREATERTHANEQUAL);
assertion.setCompOper(SizeAssertion.ComparisonOperator.GREATERTHANEQUAL.getValue());
assertion.setAllowedSize(0);
result = assertion.getResult(sample1);
assertPassed();
@ -127,7 +127,7 @@ public class SizeAssertionTest extends JMeterTestCase {
@Test
public void testSizeAssertionLessThan() throws Exception {
assertion.setCompOper(SizeAssertion.LESSTHAN);
assertion.setCompOper(SizeAssertion.ComparisonOperator.LESSTHAN.getValue());
assertion.setAllowedSize(0);
result = assertion.getResult(sample1);
assertFailed();
@ -145,7 +145,7 @@ public class SizeAssertionTest extends JMeterTestCase {
@Test
public void testSizeAssertionLessThanEqual() throws Exception {
assertion.setCompOper(SizeAssertion.LESSTHANEQUAL);
assertion.setCompOper(SizeAssertion.ComparisonOperator.LESSTHANEQUAL.getValue());
assertion.setAllowedSize(0);
result = assertion.getResult(sample1);
assertFailed();

View File

@ -86,8 +86,10 @@ class TestJSONPostProcessor {
processor.setJsonPathExpressions(path);
processor.setRefNames("result");
accessMode.configure(processor);
SampleResult sampleResult = createSampleResult("{\"a\": 23, \"b\": \"parent_only\"}");
sampleResult.addSubResult(createSampleResult("{\"a\": 42, \"c\": \"child_only\"}"));
SampleResult sampleResult = createSampleResult("""
{"a": 23, "b": "parent_only"}""");
sampleResult.addSubResult(createSampleResult("""
{"a": 42, "c": "child_only"}"""));
context.setPreviousResult(sampleResult);
context.setVariables(vars);
processor.process();
@ -297,7 +299,8 @@ class TestJSONPostProcessor {
void testExtractComplexElements() {
JMeterContext context = JMeterContextService.getContext();
JSONPostProcessor processor = setupProcessor(context, "-1");
String data = "[{\"a\":[1,{\"d\":2},3]},[\"b\",{\"h\":23}],3]";
String data = """
[{"a":[1,{"d":2},3]},["b",{"h":23}],3]""";
SampleResult result = new SampleResult();
result.setResponseData(data.getBytes(StandardCharsets.UTF_8));
JMeterVariables vars = new JMeterVariables();
@ -310,8 +313,10 @@ class TestJSONPostProcessor {
String jsonWithoutOuterParens = data.substring(1, data.length() - 1);
assertEquals(jsonWithoutOuterParens, vars.get(VAR_NAME + "_ALL"));
assertEquals("{\"a\":[1,{\"d\":2},3]}", vars.get(VAR_NAME + "_1"));
assertEquals("[\"b\",{\"h\":23}]", vars.get(VAR_NAME + "_2"));
assertEquals("""
{"a":[1,{"d":2},3]}""", vars.get(VAR_NAME + "_1"));
assertEquals("""
["b",{"h":23}]""", vars.get(VAR_NAME + "_2"));
assertEquals("3", vars.get(VAR_NAME + "_3"));
assertEquals("3", vars.get(VAR_NAME + "_matchNr"));

View File

@ -185,13 +185,13 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
@Override
public void configure(HashTree testTree) {
// Is testplan serialised?
SearchByClass<TestPlan> testPlan = new SearchByClass<>(TestPlan.class);
var testPlan = new SearchByClass<>(TestPlan.class);
testTree.traverse(testPlan);
Object[] plan = testPlan.getSearchResults().toArray();
var plan = testPlan.getSearchResults().toArray();
if (plan.length == 0) {
throw new IllegalStateException("Could not find the TestPlan class!");
}
TestPlan tp = (TestPlan) plan[0];
var tp = (TestPlan) plan[0];
serialized = tp.isSerialized();
tearDownOnShutdown = tp.isTearDownOnShutdown();
active = true;
@ -409,7 +409,7 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
JMeterContextService.startTest();
try {
PreCompiler compiler = new PreCompiler();
var compiler = new PreCompiler();
test.traverse(compiler);
} catch (RuntimeException e) {
log.error("Error occurred compiling the tree:",e);
@ -420,7 +420,7 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
* Notification of test listeners needs to happen after function
* replacement, but before setting RunningVersion to true.
*/
SearchByClass<TestStateListener> testListeners = new SearchByClass<>(TestStateListener.class); // TL - S&E
var testListeners = new SearchByClass<>(TestStateListener.class); // TL - S&E
test.traverse(testListeners);
// Merge in any additional test listeners
@ -431,12 +431,12 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
test.traverse(new TurnElementsOn());
notifyTestListenersOfStart(testListeners);
List<?> testLevelElements = new ArrayList<>(test.list(test.getArray()[0]));
var testLevelElements = new ArrayList<>(test.list(test.getArray()[0]));
removeThreadGroups(testLevelElements);
SearchByClass<SetupThreadGroup> setupSearcher = new SearchByClass<>(SetupThreadGroup.class);
SearchByClass<AbstractThreadGroup> searcher = new SearchByClass<>(AbstractThreadGroup.class);
SearchByClass<PostThreadGroup> postSearcher = new SearchByClass<>(PostThreadGroup.class);
var setupSearcher = new SearchByClass<>(SetupThreadGroup.class);
var searcher = new SearchByClass<>(AbstractThreadGroup.class);
var postSearcher = new SearchByClass<>(PostThreadGroup.class);
test.traverse(setupSearcher);
test.traverse(searcher);
@ -446,11 +446,11 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
// for each thread group, generate threads
// hand each thread the sampler controller
// and the listeners, and the timer
Iterator<SetupThreadGroup> setupIter = setupSearcher.getSearchResults().iterator();
Iterator<AbstractThreadGroup> iter = searcher.getSearchResults().iterator();
Iterator<PostThreadGroup> postIter = postSearcher.getSearchResults().iterator();
var setupIter = setupSearcher.getSearchResults().iterator();
var iter = searcher.getSearchResults().iterator();
var postIter = postSearcher.getSearchResults().iterator();
ListenerNotifier notifier = new ListenerNotifier();
var notifier = new ListenerNotifier();
int groupCount = 0;
JMeterContextService.clearTotalThreads();
@ -458,9 +458,9 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
if (setupIter.hasNext()) {
log.info("Starting setUp thread groups");
while (running && setupIter.hasNext()) {//for each setup thread group
AbstractThreadGroup group = setupIter.next();
var group = setupIter.next();
groupCount++;
String groupName = group.getName();
var groupName = group.getName();
log.info("Starting setUp ThreadGroup: {} : {} ", groupCount, groupName);
startThreadGroup(group, groupCount, setupSearcher, testLevelElements, notifier);
if (serialized && setupIter.hasNext()) {
@ -489,7 +489,7 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
JMeterContextService.getContext().setSamplingStarted(true);
boolean mainGroups = running; // still running at this point, i.e. setUp was not cancelled
while (running && iter.hasNext()) {// for each thread group
AbstractThreadGroup group = iter.next();
var group = iter.next();
//ignore Setup and Post here. We could have filtered the searcher. but then
//future Thread Group objects wouldn't execute.
if (group instanceof SetupThreadGroup ||
@ -497,7 +497,7 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
continue;
}
groupCount++;
String groupName = group.getName();
var groupName = group.getName();
log.info("Starting ThreadGroup: {} : {}", groupCount, groupName);
startThreadGroup(group, groupCount, searcher, testLevelElements, notifier);
if (serialized && iter.hasNext()) {
@ -527,9 +527,9 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
running = tearDownOnShutdown; // re-enable for tearDown if necessary
}
while (running && postIter.hasNext()) {//for each setup thread group
AbstractThreadGroup group = postIter.next();
var group = postIter.next();
groupCount++;
String groupName = group.getName();
var groupName = group.getName();
log.info("Starting tearDown ThreadGroup: {} : {}", groupCount, groupName);
startThreadGroup(group, groupCount, postSearcher, testLevelElements, notifier);
if (serialized && postIter.hasNext()) {
@ -557,7 +557,7 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
boolean onErrorStopTestNow = group.getOnErrorStopTestNow();
boolean onErrorStopThread = group.getOnErrorStopThread();
boolean onErrorStartNextLoop = group.getOnErrorStartNextLoop();
String groupName = group.getName();
var groupName = group.getName();
log.info("Starting {} threads for group {}.", numThreads, groupName);
if (onErrorStopTest) {
log.info("Test will stop on error");
@ -570,7 +570,7 @@ public class StandardJMeterEngine implements JMeterEngine, Runnable {
} else {
log.info("Thread will continue on error");
}
ListedHashTree threadGroupTree = (ListedHashTree) searcher.getSubTree(group);
var threadGroupTree = (ListedHashTree) searcher.getSubTree(group);
threadGroupTree.add(group, testLevelElements);
groups.add(group);

View File

@ -432,13 +432,12 @@ public final class GuiPackage implements LocaleChangeListener, HistoryListener {
}
private void updateUi(JMeterGUIComponent comp) {
if (!(comp instanceof JComponent)) {
if (!(comp instanceof JComponent jc)) {
return;
}
JComponent jc = (JComponent) comp;
Object epoch = jc.getClientProperty(LAF_EPOCH);
int currentLafEpoch = lafEpoch.get();
if (epoch instanceof Integer && ((Integer) epoch) < currentLafEpoch) {
if (epoch instanceof Integer epochInt && epochInt < currentLafEpoch) {
JFactory.updateUi(jc);
}
jc.putClientProperty(LAF_EPOCH, currentLafEpoch);

View File

@ -228,10 +228,10 @@ public final class CSVSaveService {
Arrays.asList(DATE_FORMAT_STRINGS));
boolean foundMatch = false;
for(String fmt : DATE_FORMAT_STRINGS) {
SimpleDateFormat dateFormat = new SimpleDateFormat(fmt);
var dateFormat = new SimpleDateFormat(fmt);
dateFormat.setLenient(false);
try {
Date stamp = dateFormat.parse(text);
var stamp = dateFormat.parse(text);
timeStamp = stamp.getTime();
log.warn("Setting date format to: {}", fmt);
saveConfig.setDateFormat(fmt);
@ -246,7 +246,7 @@ public final class CSVSaveService {
}
}
} else if (saveConfig.strictDateFormatter() != null) {
Date stamp = saveConfig.strictDateFormatter().parse(text);
var stamp = saveConfig.strictDateFormatter().parse(text);
timeStamp = stamp.getTime();
} else { // can this happen?
final String msg = "Unknown timestamp format";

View File

@ -84,23 +84,14 @@ public class SampleSaveConfigurationConverter extends ReflectionConverter {
}
// These are new fields; not saved unless true
// This list MUST agree with the list in the marshall() method below
switch (fieldName) {
case NODE_BYTES:
case NODE_SENT_BYTES:
case NODE_URL:
case NODE_FILENAME:
case NODE_HOSTNAME:
case NODE_THREAD_COUNT:
case NODE_SAMPLE_COUNT:
case NODE_IDLE_TIME:
case NODE_CONNECT_TIME:
return switch (fieldName) {
case NODE_BYTES, NODE_SENT_BYTES, NODE_URL, NODE_FILENAME,
NODE_HOSTNAME, NODE_THREAD_COUNT, NODE_SAMPLE_COUNT,
NODE_IDLE_TIME, NODE_CONNECT_TIME,
// The two fields below are not currently saved or restored
case NODE_DELIMITER:
case NODE_PRINTMS:
return false;
default:
return true;
}
NODE_DELIMITER, NODE_PRINTMS -> false;
default -> true;
};
}
}

View File

@ -174,18 +174,18 @@ public class TestBeanHelper {
private static Object unwrapProperty(PropertyDescriptor desc, JMeterProperty jprop, Class<?> type) {
Object value;
if(jprop instanceof TestElementProperty)
if(jprop instanceof TestElementProperty testElementProperty)
{
TestElement te = ((TestElementProperty)jprop).getElement();
TestElement te = testElementProperty.getElement();
if(te instanceof TestBean)
{
prepare(te);
}
value = te;
}
else if(jprop instanceof MultiProperty)
else if(jprop instanceof MultiProperty multiProperty)
{
value = unwrapCollection((MultiProperty)jprop,(String)desc.getValue(TableEditor.CLASSNAME));
value = unwrapCollection(multiProperty,(String)desc.getValue(TableEditor.CLASSNAME));
}
// value was not provided, and this is allowed
else if (jprop instanceof NullProperty &&
@ -200,10 +200,10 @@ public class TestBeanHelper {
private static Object unwrapCollection(MultiProperty prop, String type)
{
if(prop instanceof CollectionProperty)
if(prop instanceof CollectionProperty collectionProperty)
{
Collection<Object> values = new ArrayList<>();
for (JMeterProperty jMeterProperty : prop) {
for (JMeterProperty jMeterProperty : collectionProperty) {
try {
values.add(unwrapProperty(null, jMeterProperty, Class.forName(type)));
}

View File

@ -236,9 +236,9 @@ public abstract class AbstractTestElement implements TestElement, Serializable,
*/
@Override
public boolean equals(Object o) {
if (o instanceof AbstractTestElement) {
if (o instanceof AbstractTestElement other) {
try (ResourceLock ignored = readLock()) {
return ((AbstractTestElement) o).propMap.equals(propMap);
return other.propMap.equals(propMap);
}
} else {
return false;

View File

@ -195,13 +195,12 @@ public abstract class AbstractProperty implements JMeterProperty {
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof JMeterProperty)) {
if (!(o instanceof JMeterProperty jpo)) {
return false;
}
if (this == o) {
return true;
}
JMeterProperty jpo = (JMeterProperty) o;
if (!name.equals(jpo.getName())) {
return false;
}
@ -275,18 +274,18 @@ public abstract class AbstractProperty implements JMeterProperty {
if (item == null) {
return new NullProperty();
}
if (item instanceof String) {
return new StringProperty("", item.toString());
} else if (item instanceof Boolean) {
return new BooleanProperty("", (Boolean) item);
} else if (item instanceof Float) {
return new FloatProperty("", (Float) item);
} else if (item instanceof Double) {
return new DoubleProperty("", (Double) item);
} else if (item instanceof Integer) {
return new IntegerProperty("", (Integer) item);
} else if (item instanceof Long) {
return new LongProperty("", (Long) item);
if (item instanceof String str) {
return new StringProperty("", str);
} else if (item instanceof Boolean bool) {
return new BooleanProperty("", bool);
} else if (item instanceof Float floatVal) {
return new FloatProperty("", floatVal);
} else if (item instanceof Double doubleVal) {
return new DoubleProperty("", doubleVal);
} else if (item instanceof Integer intVal) {
return new IntegerProperty("", intVal);
} else if (item instanceof Long longVal) {
return new LongProperty("", longVal);
} else {
return new StringProperty("", item.toString());
}
@ -341,8 +340,8 @@ public abstract class AbstractProperty implements JMeterProperty {
Object key = entry.getKey();
Object prop = entry.getValue();
String item=null;
if (key instanceof String) {
item = (String) key;
if (key instanceof String keyStr) {
item = keyStr;
} else {
if (key != null) {
log.error("Expected key type String, found: {}", key.getClass());
@ -378,18 +377,17 @@ public abstract class AbstractProperty implements JMeterProperty {
* @return the JMeterProperty
*/
protected static JMeterProperty makeProperty(Object item) {
if (item instanceof JMeterProperty) {
return (JMeterProperty) item;
if (item instanceof JMeterProperty prop) {
return prop;
}
if (item instanceof TestElement) {
return new TestElementProperty(((TestElement) item).getName(),
(TestElement) item);
if (item instanceof TestElement testElement) {
return new TestElementProperty(testElement.getName(), testElement);
}
if (item instanceof Collection<?>) {
return new CollectionProperty(Integer.toString(item.hashCode()), (Collection<?>) item);
if (item instanceof Collection<?> collection) {
return new CollectionProperty(Integer.toString(item.hashCode()), collection);
}
if (item instanceof Map<?, ?>) {
return new MapProperty(Integer.toString(item.hashCode()), (Map<?, ?>) item);
if (item instanceof Map<?, ?> map) {
return new MapProperty(Integer.toString(item.hashCode()), map);
}
return null;
}

View File

@ -66,27 +66,27 @@ public class CollectionProperty extends MultiProperty {
}
public void set(int index, String prop) {
if (value instanceof List<?>) {
((List<JMeterProperty>) value).set(index, new StringProperty(prop, prop));
if (value instanceof List<JMeterProperty> list) {
list.set(index, new StringProperty(prop, prop));
}
}
public void set(int index, JMeterProperty prop) {
if (value instanceof List<?>) {
((List<JMeterProperty>) value).set(index, prop);
if (value instanceof List<JMeterProperty> list) {
list.set(index, prop);
}
}
public JMeterProperty get(int row) {
if (value instanceof List<?>) {
return ((List<JMeterProperty>) value).get(row);
if (value instanceof List<JMeterProperty> list) {
return list.get(row);
}
return null;
}
public void remove(int index) {
if (value instanceof List<?>) {
((List<?>) value).remove(index);
if (value instanceof List<?> list) {
list.remove(index);
}
}

View File

@ -355,8 +355,8 @@ public class JMeterThread implements Runnable, Interruptible {
private void triggerLoopLogicalActionOnParentControllers(Sampler sampler, JMeterContext threadContext,
Consumer<? super FindTestElementsUpToRootTraverser> consumer) {
TransactionSampler transactionSampler = null;
if (sampler instanceof TransactionSampler) {
transactionSampler = (TransactionSampler) sampler;
if (sampler instanceof TransactionSampler transSampler) {
transactionSampler = transSampler;
}
Sampler realSampler = findRealSampler(sampler);
@ -389,11 +389,10 @@ public class JMeterThread implements Runnable, Interruptible {
private static void continueOnCurrentLoop(FindTestElementsUpToRootTraverser pathToRootTraverser) {
List<Controller> controllersToReinit = pathToRootTraverser.getControllersToRoot();
for (Controller parentController : controllersToReinit) {
if (parentController instanceof AbstractThreadGroup) {
AbstractThreadGroup tg = (AbstractThreadGroup) parentController;
if (parentController instanceof AbstractThreadGroup tg) {
tg.startNextLoop();
} else if (parentController instanceof IteratingController) {
((IteratingController) parentController).startNextLoop();
} else if (parentController instanceof IteratingController iterController) {
iterController.startNextLoop();
break;
} else {
parentController.triggerEndOfLoop();
@ -409,11 +408,10 @@ public class JMeterThread implements Runnable, Interruptible {
private static void breakOnCurrentLoop(FindTestElementsUpToRootTraverser pathToRootTraverser) {
List<Controller> controllersToReinit = pathToRootTraverser.getControllersToRoot();
for (Controller parentController : controllersToReinit) {
if (parentController instanceof AbstractThreadGroup) {
AbstractThreadGroup tg = (AbstractThreadGroup) parentController;
if (parentController instanceof AbstractThreadGroup tg) {
tg.breakThreadLoop();
} else if (parentController instanceof IteratingController) {
((IteratingController) parentController).breakLoop();
} else if (parentController instanceof IteratingController iterController) {
iterController.breakLoop();
break;
} else {
parentController.triggerEndOfLoop();
@ -448,8 +446,8 @@ public class JMeterThread implements Runnable, Interruptible {
*/
private static Sampler findRealSampler(Sampler sampler) {
Sampler realSampler = sampler;
while (realSampler instanceof TransactionSampler) {
realSampler = ((TransactionSampler) realSampler).getSubSampler();
while (realSampler instanceof TransactionSampler transSampler) {
realSampler = transSampler.getSubSampler();
}
return realSampler;
}
@ -469,8 +467,8 @@ public class JMeterThread implements Runnable, Interruptible {
// Find the package for the transaction
SamplePackage transactionPack = null;
try {
if (current instanceof TransactionSampler) {
transactionSampler = (TransactionSampler) current;
if (current instanceof TransactionSampler transSampler) {
transactionSampler = transSampler;
transactionPack = compiler.configureTransactionSampler(transactionSampler);
// Check if the transaction is done
@ -641,8 +639,8 @@ public class JMeterThread implements Runnable, Interruptible {
currentSamplerForInterruption = sampler;
if (!sampleMonitors.isEmpty()) {
for (SampleMonitor sampleMonitor : sampleMonitors) {
if(sampleMonitor instanceof TestElement) {
TestBeanHelper.prepare((TestElement) sampleMonitor);
if(sampleMonitor instanceof TestElement testElement) {
TestBeanHelper.prepare(testElement);
}
sampleMonitor.sampleStarting(sampler);
}
@ -795,8 +793,7 @@ public class JMeterThread implements Runnable, Interruptible {
@Override
public void addNode(Object node, HashTree subTree) {
if (node instanceof ThreadListener) {
ThreadListener tl = (ThreadListener) node;
if (node instanceof ThreadListener tl) {
if (isStart) {
try {
tl.threadStarted();
@ -902,8 +899,7 @@ public class JMeterThread implements Runnable, Interruptible {
private static void checkAssertions(List<? extends Assertion> assertions, SampleResult parent, JMeterContext threadContext) {
for (Assertion assertion : assertions) {
TestBeanHelper.prepare((TestElement) assertion);
if (assertion instanceof AbstractScopedAssertion) {
AbstractScopedAssertion scopedAssertion = (AbstractScopedAssertion) assertion;
if (assertion instanceof AbstractScopedAssertion scopedAssertion) {
String scope = scopedAssertion.fetchScope();
if (scopedAssertion.isScopeParent(scope)
|| scopedAssertion.isScopeAll(scope)
@ -1031,8 +1027,8 @@ public class JMeterThread implements Runnable, Interruptible {
threadVars.incIteration();
for (TestIterationListener listener : testIterationStartListeners) {
listener.testIterationStart(new LoopIterationEvent(threadGroupLoopController, threadVars.getIteration()));
if (listener instanceof TestElement) {
((TestElement) listener).recoverRunningVersion();
if (listener instanceof TestElement testElement) {
testElement.recoverRunningVersion();
}
}
}

View File

@ -136,11 +136,11 @@ public class TestCompiler implements HashTreeTraverser {
}
TestElement child = stack.getLast();
trackIterationListeners(stack);
if (child instanceof Sampler) {
saveSamplerConfigs((Sampler) child);
if (child instanceof Sampler sampler) {
saveSamplerConfigs(sampler);
}
else if(child instanceof TransactionController) {
saveTransactionControllerConfigs((TransactionController) child);
else if(child instanceof TransactionController transactionController) {
saveTransactionControllerConfigs(transactionController);
}
stack.removeLast();
if (!stack.isEmpty()) {
@ -148,8 +148,7 @@ public class TestCompiler implements HashTreeTraverser {
boolean duplicate = false;
// Bug 53750: this condition used to be in ObjectPair#addTestElements()
if (parent instanceof Controller && (child instanceof Sampler || child instanceof Controller)) {
if (parent instanceof TestCompilerHelper) {
TestCompilerHelper te = (TestCompilerHelper) parent;
if (parent instanceof TestCompilerHelper te) {
duplicate = !te.addTestElementOnce(child);
} else { // this is only possible for 3rd party controllers by default
ObjectPair pair = new ObjectPair(child, parent);
@ -174,16 +173,16 @@ public class TestCompiler implements HashTreeTraverser {
@SuppressWarnings("NonApiType")
private static void trackIterationListeners(LinkedList<TestElement> pStack) {
TestElement child = pStack.getLast();
if (child instanceof LoopIterationListener) {
if (child instanceof LoopIterationListener loopListener) {
ListIterator<TestElement> iter = pStack.listIterator(pStack.size());
while (iter.hasPrevious()) {
TestElement item = iter.previous();
if (item == child) {
continue;
}
if (item instanceof Controller) {
if (item instanceof Controller controller) {
TestBeanHelper.prepare(child);
((Controller) item).addIterationListener((LoopIterationListener) child);
controller.addIterationListener(loopListener);
break;
}
}
@ -209,23 +208,23 @@ public class TestCompiler implements HashTreeTraverser {
List<PostProcessor> tempPost = new ArrayList<>();
List<Assertion> tempAssertions = new ArrayList<>();
for (Object item : testTree.list(stack.subList(0, i))) {
if (item instanceof ConfigTestElement) {
configs.add((ConfigTestElement) item);
if (item instanceof ConfigTestElement configElement) {
configs.add(configElement);
}
if (item instanceof SampleListener) {
listeners.add((SampleListener) item);
if (item instanceof SampleListener listener) {
listeners.add(listener);
}
if (item instanceof Timer) {
timers.add((Timer) item);
if (item instanceof Timer timer) {
timers.add(timer);
}
if (item instanceof Assertion) {
tempAssertions.add((Assertion) item);
if (item instanceof Assertion assertion) {
tempAssertions.add(assertion);
}
if (item instanceof PostProcessor) {
tempPost.add((PostProcessor) item);
if (item instanceof PostProcessor postProcessor) {
tempPost.add(postProcessor);
}
if (item instanceof PreProcessor) {
tempPre.add((PreProcessor) item);
if (item instanceof PreProcessor preProcessor) {
tempPre.add(preProcessor);
}
}
assertions.addAll(0, tempAssertions);
@ -251,11 +250,11 @@ public class TestCompiler implements HashTreeTraverser {
for (int i = stack.size(); i > 0; i--) {
addDirectParentControllers(controllers, stack.get(i - 1));
for (Object item : testTree.list(stack.subList(0, i))) {
if (item instanceof SampleListener) {
listeners.add((SampleListener) item);
if (item instanceof SampleListener listener) {
listeners.add(listener);
}
if (item instanceof Assertion) {
assertions.add((Assertion) item);
if (item instanceof Assertion assertion) {
assertions.add(assertion);
}
}
}
@ -272,9 +271,9 @@ public class TestCompiler implements HashTreeTraverser {
* @param maybeController
*/
private static void addDirectParentControllers(List<? super Controller> controllers, TestElement maybeController) {
if (maybeController instanceof Controller) {
if (maybeController instanceof Controller controller) {
log.debug("adding controller: {} to sampler config", maybeController);
controllers.add((Controller) maybeController);
controllers.add(controller);
}
}
@ -297,8 +296,8 @@ public class TestCompiler implements HashTreeTraverser {
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (o instanceof ObjectPair) {
return child == ((ObjectPair) o).child && parent == ((ObjectPair) o).parent;
if (o instanceof ObjectPair other) {
return child == other.child && parent == other.parent;
}
return false;
}
@ -309,8 +308,8 @@ public class TestCompiler implements HashTreeTraverser {
for (ConfigTestElement config : configs) {
if (!(config instanceof NoConfigMerge))
{
if(sam instanceof ConfigMergabilityIndicator) {
if(((ConfigMergabilityIndicator)sam).applies(config)) {
if(sam instanceof ConfigMergabilityIndicator indicator) {
if(indicator.applies(config)) {
sam.addTestElement(config);
}
} else {

View File

@ -80,25 +80,18 @@ public class ChangeCase extends AbstractFunction {
}
protected String changeCase(String originalString, String mode) {
String targetString = originalString;
// mode is case insensitive, allow upper for example
ChangeCaseMode changeCaseMode = ChangeCaseMode.typeOf(mode.toUpperCase(Locale.ROOT));
if (changeCaseMode != null) {
switch (changeCaseMode) {
case UPPER:
targetString = StringUtils.upperCase(originalString);
break;
case LOWER:
targetString = StringUtils.lowerCase(originalString);
break;
case CAPITALIZE:
targetString = StringUtils.capitalize(originalString);
break;
if (changeCaseMode == null) {
LOGGER.error("Unknown mode {}, returning {} unchanged", mode, originalString);
return originalString;
}
} else {
LOGGER.error("Unknown mode {}, returning {} unchanged", mode, targetString);
}
return targetString;
return switch (changeCaseMode) {
case UPPER -> StringUtils.upperCase(originalString);
case LOWER -> StringUtils.lowerCase(originalString);
case CAPITALIZE -> StringUtils.capitalize(originalString);
};
}
@Override

View File

@ -57,9 +57,9 @@ public class CharFunction extends AbstractFunction {
public String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
StringBuilder sb = new StringBuilder(values.length);
var sb = new StringBuilder(values.length);
for (Object val : values) {
String numberString = ((CompoundVariable) val).execute().trim();
var numberString = ((CompoundVariable) val).execute().trim();
try {
long value = Long.decode(numberString);
char ch = (char) value;

View File

@ -164,21 +164,11 @@ public class LogFunction extends AbstractFunction {
final String separator = comment.isEmpty() ? DEFAULT_SEPARATOR : comment;
switch (prioLevel) {
case ERROR:
logger.error("{} {} {}", threadName, separator, stringToLog, throwable);
break;
case WARN:
logger.warn("{} {} {}", threadName, separator, stringToLog, throwable);
break;
case INFO:
logger.info("{} {} {}", threadName, separator, stringToLog, throwable);
break;
case DEBUG:
logger.debug("{} {} {}", threadName, separator, stringToLog, throwable);
break;
case TRACE:
logger.trace("{} {} {}", threadName, separator, stringToLog, throwable);
break;
case ERROR -> logger.error("{} {} {}", threadName, separator, stringToLog, throwable);
case WARN -> logger.warn("{} {} {}", threadName, separator, stringToLog, throwable);
case INFO -> logger.info("{} {} {}", threadName, separator, stringToLog, throwable);
case DEBUG -> logger.debug("{} {} {}", threadName, separator, stringToLog, throwable);
case TRACE -> logger.trace("{} {} {}", threadName, separator, stringToLog, throwable);
}
}
}

View File

@ -182,8 +182,8 @@ public class RegexFunction extends AbstractFunction {
}
if (valueIndex.equals(ALL)) {
StringBuilder value = new StringBuilder();
Iterator<java.util.regex.MatchResult> it = collectAllMatches.iterator();
var value = new StringBuilder();
var it = collectAllMatches.iterator();
boolean first = true;
while (it.hasNext()) {
if (!first) {
@ -195,7 +195,7 @@ public class RegexFunction extends AbstractFunction {
}
return value.toString();
} else if (valueIndex.equals(RAND)) {
java.util.regex.MatchResult result = collectAllMatches.get(
var result = collectAllMatches.get(
ThreadLocalRandom.current().nextInt(collectAllMatches.size()));
return generateResult(result, name, tmplt, vars);
} else {
@ -313,7 +313,7 @@ public class RegexFunction extends AbstractFunction {
private static String generateResult(MatchResult match, String namep, Object[] template, JMeterVariables vars) {
saveGroups(match, namep, vars);
StringBuilder result = new StringBuilder();
var result = new StringBuilder();
for (Object t : template) {
if (t instanceof String) {
result.append(t);

View File

@ -296,7 +296,7 @@ public class StringFromFile extends AbstractFunction implements TestStateListene
checkParameterCount(parameters, MIN_PARAM_COUNT, MAX_PARAM_COUNT);
values = parameters.toArray();
StringBuilder sb = new StringBuilder(40);
var sb = new StringBuilder(40);
sb.append("setParameters(");//$NON-NLS-1$
for (int i = 0; i < values.length; i++) {
if (i > 0) {

View File

@ -95,8 +95,10 @@ public class HashTree implements Serializable, Map<Object, HashTree>, Cloneable
*/
private HashTree(Map<Object, ? extends HashTree> _map, Object key) {
if(_map != null) {
if (_map instanceof IdentityHashMap) {
data = (IdentityHashMap<Object, HashTree>) _map;
if (_map instanceof IdentityHashMap<?, ?> identityMapRaw) {
@SuppressWarnings("unchecked")
IdentityHashMap<Object, HashTree> identityMap = (IdentityHashMap<Object, HashTree>) identityMapRaw;
data = identityMap;
} else {
// Technically speaking, TestElements can't be placed in HashMapk keys,
// so we have to convert the map to an IdentityHashMap.
@ -122,8 +124,8 @@ public class HashTree implements Serializable, Map<Object, HashTree>, Cloneable
*/
@Override
public void putAll(Map<?, ? extends HashTree> map) {
if (map instanceof HashTree) {
this.add((HashTree) map);
if (map instanceof HashTree hashTree) {
this.add(hashTree);
} else {
throw new UnsupportedOperationException("can only putAll other HashTree objects");
}
@ -916,7 +918,7 @@ public class HashTree implements Serializable, Map<Object, HashTree>, Cloneable
if (o == this) {
return true;
}
if (!(o instanceof HashTree)) {
if (!(o instanceof HashTree hashTree)) {
return false;
}
HashTree oo = (HashTree) o;

View File

@ -90,8 +90,8 @@ public class Converter {
*/
public static Calendar getCalendar(Object date, Calendar defaultValue) {
Calendar cal = new GregorianCalendar();
if (date instanceof java.util.Date) {
cal.setTime((java.util.Date) date);
if (date instanceof java.util.Date dateValue) {
cal.setTime(dateValue);
return cal;
} else if (date != null) {
Optional<Date> d = tryToParseDate(date);
@ -145,8 +145,8 @@ public class Converter {
* <code>defaultValue</code> if conversion failed
*/
public static Date getDate(Object date, Date defaultValue) {
if (date instanceof java.util.Date) {
return (Date) date;
if (date instanceof java.util.Date dateValue) {
return dateValue;
} else if (date != null) {
return tryToParseDate(date).orElse(defaultValue);
} else {
@ -182,8 +182,8 @@ public class Converter {
if (o == null) {
return defaultValue;
}
if (o instanceof Number) {
return ((Number) o).floatValue();
if (o instanceof Number number) {
return number.floatValue();
}
try {
return Float.parseFloat(o.toString());
@ -221,8 +221,8 @@ public class Converter {
if (o == null) {
return defaultValue;
}
if (o instanceof Number) {
return ((Number) o).doubleValue();
if (o instanceof Number number) {
return number.doubleValue();
}
return Double.parseDouble(o.toString());
} catch (NumberFormatException e) {
@ -270,8 +270,8 @@ public class Converter {
public static boolean getBoolean(Object o, boolean defaultValue) {
if (o == null) {
return defaultValue;
} else if (o instanceof Boolean) {
return (Boolean) o;
} else if (o instanceof Boolean boolValue) {
return boolValue;
}
return Boolean.parseBoolean(o.toString());
}
@ -291,8 +291,8 @@ public class Converter {
if (o == null) {
return defaultValue;
}
if (o instanceof Number) {
return ((Number) o).intValue();
if (o instanceof Number number) {
return number.intValue();
}
return Integer.parseInt(o.toString());
} catch (NumberFormatException e) {
@ -327,12 +327,12 @@ public class Converter {
if (o == null) {
return defaultValue;
}
if (o instanceof Character) {
return (Character) o;
} else if (o instanceof Byte) {
return (char) ((Byte) o).byteValue();
} else if (o instanceof Integer) {
return (char) ((Integer) o).intValue();
if (o instanceof Character charValue) {
return charValue;
} else if (o instanceof Byte byteValue) {
return (char) byteValue.byteValue();
} else if (o instanceof Integer intValue) {
return (char) intValue.intValue();
} else {
String s = o.toString();
if (s.length() > 0) {
@ -373,8 +373,8 @@ public class Converter {
if (o == null) {
return defaultValue;
}
if (o instanceof Number) {
return ((Number) o).longValue();
if (o instanceof Number number) {
return number.longValue();
}
return Long.parseLong(o.toString());
} catch (NumberFormatException e) {
@ -546,11 +546,11 @@ public class Converter {
* when object can not be converted
*/
public static File getFile(Object o){
if (o instanceof File) {
return (File) o;
if (o instanceof File file) {
return file;
}
if (o instanceof String) {
return new File((String) o);
if (o instanceof String str) {
return new File(str);
}
throw new IllegalArgumentException("Expected String or file, actual "+o.getClass().getName());
}

View File

@ -211,8 +211,8 @@ public class CacheManager extends ConfigTestElement implements TestStateListener
if (headerName == null) {
return null;
}
final Set<String> names = new HashSet<>(Arrays.asList(headerName.split(",\\s*")));
final Map<String, List<String>> values = new HashMap<>();
final var names = new HashSet<>(Arrays.asList(headerName.split(",\\s*")));
final var values = new HashMap<String, List<String>>();
for (final String name: names) {
values.put(name, new ArrayList<>());
}

View File

@ -287,19 +287,12 @@ public class BasicCurlParser {
public void setLimitRate(String limitRate) {
String unit = limitRate.substring(limitRate.length() - 1, limitRate.length()).toLowerCase(Locale.ROOT);
int value = Integer.parseInt(limitRate.substring(0, limitRate.length() - 1).toLowerCase(Locale.ROOT));
switch (unit) {
case "k":
this.limitRate = value * ONE_KILOBYTE_IN_CPS;
break;
case "m":
this.limitRate = value * ONE_KILOBYTE_IN_CPS * 1000;
break;
case "g":
this.limitRate = value * ONE_KILOBYTE_IN_CPS * 1000000;
break;
default:
break;
}
this.limitRate = switch (unit) {
case "k" -> value * ONE_KILOBYTE_IN_CPS;
case "m" -> value * ONE_KILOBYTE_IN_CPS * 1000;
case "g" -> value * ONE_KILOBYTE_IN_CPS * 1000000;
default -> this.limitRate; // Keep current value if unit is not recognized
};
}
/**
@ -640,8 +633,9 @@ public class BasicCurlParser {
"Tells curl to use HTTP negotiate authentication when communicating with the given proxy. ");
private static final CLOptionDescriptor D_KEEPALIVETILE_OPT = new CLOptionDescriptor("keepalive-time",
CLOptionDescriptor.ARGUMENT_REQUIRED, KEEPALIVETILE_OPT,
" This option sets the time a connection needs to remain idle before sending"
+ " keepalive probes and the time between individual keepalive probes..");
"""
This option sets the time a connection needs to remain idle before sending \
keepalive probes and the time between individual keepalive probes..""");
private static final CLOptionDescriptor D_MAX_TIME_OPT = new CLOptionDescriptor("max-time",
CLOptionDescriptor.ARGUMENT_REQUIRED, MAX_TIME_OPT,
"Maximum time in seconds that you allow the whole operation to take. ");
@ -652,8 +646,9 @@ public class BasicCurlParser {
"Create the necessary local directory hierarchy as needed for output file");
private static final CLOptionDescriptor D_RAW_OPT = new CLOptionDescriptor("raw",
CLOptionDescriptor.ARGUMENT_DISALLOWED, RAW_OPT,
"When used, it disables all internal HTTP decoding of content or transfer encodings "
+ "and instead makes them passed on unaltered raw. ");
"""
When used, it disables all internal HTTP decoding of content or transfer \
encodings and instead makes them passed on unaltered raw.""");
private static final CLOptionDescriptor D_INTERFACE_OPT = new CLOptionDescriptor("interface",
CLOptionDescriptor.ARGUMENT_REQUIRED, INTERFACE_OPT, "Perform an operation using a specified interface");
private static final CLOptionDescriptor D_DNS_RESOLVER_OPT = new CLOptionDescriptor("resolve",

View File

@ -119,20 +119,12 @@ public class ConversionUtils {
StringBuilder sb = new StringBuilder(value.length() + 2);
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"':
sb.append("%22");
break;
case 0x0A:
sb.append("%0A");
break;
case 0x0D:
sb.append("%0D");
break;
default:
sb.append(c);
break;
}
sb.append(switch (c) {
case '"' -> "%22";
case 0x0A -> "%0A";
case 0x0D -> "%0D";
default -> String.valueOf(c);
});
}
return sb.toString();
}

View File

@ -286,10 +286,10 @@ public class RequestViewHTTP implements RequestView {
//TODO: move to utils class (JMeterUtils?)
public static Map<String, String[]> getQueryMap(String query) {
Map<String, String[]> map = new HashMap<>();
String[] params = query.split(PARAM_CONCATENATE);
var map = new HashMap<String, String[]>();
var params = query.split(PARAM_CONCATENATE);
for (String param : params) {
String[] paramSplit = param.split("=");
var paramSplit = param.split("=");
if (paramSplit.length == 0) {
continue; // We found no key-/value-pair, so continue on the next param
}

View File

@ -76,12 +76,13 @@ public class TestHttpRequestHdr extends JMeterTestCase {
// A HTTP POST request
contentEncoding = "UTF-8";
String postBody = "update=yes&d=1&d=2&d=&d=&d=&d=&d=&d=1&d=2&d=1&d=&d=";
String testPostRequest = "POST " + url + " HTTP/1.0\n"
+ "Content-type: "
+ HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED + "\r\n"
+ "Content-length: " + getBodyLength(postBody, contentEncoding) + "\r\n"
+ "\r\n"
+ postBody;
String testPostRequest = """
POST %s HTTP/1.0
Content-type: %s\r
Content-length: %d\r
\r
%s""".formatted(url, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED,
getBodyLength(postBody, contentEncoding), postBody);
s = getSamplerForRequest(url, testPostRequest, contentEncoding);
assertEquals(HTTPConstants.POST, s.getMethod());
assertFalse(s.getDoMultipart());
@ -147,35 +148,37 @@ public class TestHttpRequestHdr extends JMeterTestCase {
// The encoding should be picked up from the header we send with the request
contentEncoding = "UTF-8";
url = "http://vmdal-hqqa9/retalixhq/GG_Implementation/ScreenEntity/ScreenEntityHTTP.aspx?Action=Save&ET=Vendor&TT=Single&Sid=1347280336092";
postBody = "<Action UIStatus=\"2\"><Vendor Id=\"9292\" HOST_ID=\"0\" VENDOR=\"9292\" TERMS_TYPE=\"No Terms\" TERMS=\"0 %\""
+ " AUTO_PRICE=\"Use System Default\" VM_VENDOR_TYPE=\"DSD Vendor\" ITEM_FORMAT=\"PLU\" COST_ENTRY_SORT=\"UPC/EAN\""
+ " VM_REPORT_SORT=\"UPC/EAN\" VM_ORDER_SORT=\"UPC/EAN\" VM_RECEIVING_SORT=\"UPC/EAN\" VM_MAX_BACK_ORDERS=\"99\""
+ " MAX_OPEN_DAYS=\"99\" PAY_BASED_ON=\"System Cost\" ORDER_COST_DATE=\"Use System Rule\" VM_CONSIDER_FREE=\"False\""
+ " VM_SHOW_DETAIL=\"False\" VM_UPDATE_COST=\"No\" RD_USE_VENDOR_CC=\"False\" BLIND_RECEIVING=\"Default\""
+ " EXCLUDE_RECEIVED_COST=\"False\" PRINT_ITEM_ADJ=\"False\" PRINT_OVERALL_ADJ=\"False\" PRINT_TAX_DETAIL=\"False\""
+ " BLOCK_PRICE_VIEW=\"False\" DELIVERY_STATUS=\"No Delivery\" AUTO_RECEIVE=\"False\" TARGET_GM_FLAG=\"%\""
+ " MINIMUM_GM_FLAG=\"%\" MARGIN_TYPE=\"Gross Margin\" HOLD_REGULAR=\"Default\" HOLD_SPECIALS=\"Default\""
+ " TRUSTING_VENDOR=\"False\" AUTO_ACCEPT=\"All\" EARLY_RCPT_AFFECTS=\"All Costs\" SBT_ELIGIBLE=\"Not eligible\""
+ " SBT_REPORTING_DAY=\"Monday\" AUTO_BALANCE_FLAG=\"$\" DAX_MANAGED=\"False\" CHANGE_ID=\"QA\" CHANGE_SOURCE=\"Manual Change\""
+ " ORIGINAL_SOURCE=\"Manual Change\" RECORD_STATUS=\"Add\" RECORD_STATUS_DATE=\"9/7/2012 8:34:58 AM\" VENDOR_NAME=\"test\""
+ " UIStatus=\"2\"/></Action>";
testPostRequest = "POST " + url + " HTTP/1.1\r\n"
+ "x-requested-with: XMLHttpRequest" + "\r\n"
+ "Accept-Language: en-us" + "\r\n"
+ "Referer: http://vmdal-hqqa9/retalixhq/GG_Implementation/ScreenEntity/ScreenEntityPage.aspx?ET=Vendor&TT=Single&"
+ "WM=2&UID=9292&Sid=1347280331908&UITH=Blue&MUID=window_0" + "\r\n"
+ "Accept: */*" + "\r\n"
+ "Content-Type: application/x-www-form-urlencoded" + "\r\n"
+ "Accept-Encoding: gzip, deflate" + "\r\n"
+ "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729;"
+ " .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; Tablet PC 2.0)" + "\r\n"
+ "Host: vmdal-hqqa9" + "\r\n"
+ "Content-Length: "+ getBodyLength(postBody, contentEncoding) + "\r\n"
+ "Proxy-Connection: Keep-Alive" + "\r\n"
+ "Pragma: no-cache" + "\r\n"
+ "Cookie: RHQ=sid=5aaeb66c-e174-4f4c-9928-83cffcc62150" + "\r\n"
+ "\r\n"
+ postBody;
postBody = """
<Action UIStatus="2">
<Vendor Id="9292" HOST_ID="0" VENDOR="9292" TERMS_TYPE="No Terms" TERMS="0 %"\
AUTO_PRICE="Use System Default" VM_VENDOR_TYPE="DSD Vendor" ITEM_FORMAT="PLU" COST_ENTRY_SORT="UPC/EAN"\
VM_REPORT_SORT="UPC/EAN" VM_ORDER_SORT="UPC/EAN" VM_RECEIVING_SORT="UPC/EAN" VM_MAX_BACK_ORDERS="99"\
MAX_OPEN_DAYS="99" PAY_BASED_ON="System Cost" ORDER_COST_DATE="Use System Rule" VM_CONSIDER_FREE="False"\
VM_SHOW_DETAIL="False" VM_UPDATE_COST="No" RD_USE_VENDOR_CC="False" BLIND_RECEIVING="Default"\
EXCLUDE_RECEIVED_COST="False" PRINT_ITEM_ADJ="False" PRINT_OVERALL_ADJ="False" PRINT_TAX_DETAIL="False"\
BLOCK_PRICE_VIEW="False" DELIVERY_STATUS="No Delivery" AUTO_RECEIVE="False" TARGET_GM_FLAG="%"\
MINIMUM_GM_FLAG="%" MARGIN_TYPE="Gross Margin" HOLD_REGULAR="Default" HOLD_SPECIALS="Default"\
TRUSTING_VENDOR="False" AUTO_ACCEPT="All" EARLY_RCPT_AFFECTS="All Costs" SBT_ELIGIBLE="Not eligible"\
SBT_REPORTING_DAY="Monday" AUTO_BALANCE_FLAG="$" DAX_MANAGED="False" CHANGE_ID="QA" CHANGE_SOURCE="Manual Change"\
ORIGINAL_SOURCE="Manual Change" RECORD_STATUS="Add" RECORD_STATUS_DATE="9/7/2012 8:34:58 AM" VENDOR_NAME="test"\
UIStatus="2"/>
</Action>""";
testPostRequest = """
POST %s HTTP/1.1\r
x-requested-with: XMLHttpRequest\r
Accept-Language: en-us\r
Referer: http://vmdal-hqqa9/retalixhq/GG_Implementation/ScreenEntity/ScreenEntityPage.aspx?ET=Vendor&TT=Single&WM=2&UID=9292&Sid=1347280331908&UITH=Blue&MUID=window_0\r
Accept: */*\r
Content-Type: application/x-www-form-urlencoded\r
Accept-Encoding: gzip, deflate\r
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; Tablet PC 2.0)\r
Host: vmdal-hqqa9\r
Content-Length: %d\r
Proxy-Connection: Keep-Alive\r
Pragma: no-cache\r
Cookie: RHQ=sid=5aaeb66c-e174-4f4c-9928-83cffcc62150\r
\r
%s""".formatted(url, getBodyLength(postBody, contentEncoding), postBody);
// Use null for url to simulate that HttpRequestHdr do not
// know the encoding for the page. Specify contentEncoding, so the
// request is "sent" using that encoding
@ -594,27 +597,34 @@ public class TestHttpRequestHdr extends JMeterTestCase {
private String createMultipartFormBody(String titleValue, String descriptionValue,
String contentEncoding, boolean includeExtraHeaders,
String boundary, String endOfLine) {
// Title multipart
String postBody = "--" + boundary + endOfLine
+ "Content-Disposition: form-data; name=\"title\"" + endOfLine;
if(includeExtraHeaders) {
postBody += "Content-Type: text/plain; charset=" + contentEncoding + endOfLine
+ "Content-Transfer-Encoding: 8bit" + endOfLine;
}
postBody += endOfLine
+ titleValue + endOfLine
+ "--" + boundary + endOfLine;
// Description multipart
postBody += "Content-Disposition: form-data; name=\"description\"" + endOfLine;
if(includeExtraHeaders) {
postBody += "Content-Type: text/plain; charset=" + contentEncoding + endOfLine
+ "Content-Transfer-Encoding: 8bit" + endOfLine;
}
postBody += endOfLine
+ descriptionValue + endOfLine
+ "--" + boundary + "--" + endOfLine;
return postBody;
String titleHeaders = includeExtraHeaders ? """
Content-Type: text/plain; charset=%s%s\
Content-Transfer-Encoding: 8bit%s""".formatted(contentEncoding, endOfLine, endOfLine) : "";
String descriptionHeaders = includeExtraHeaders ? """
Content-Type: text/plain; charset=%s%s\
Content-Transfer-Encoding: 8bit%s""".formatted(contentEncoding, endOfLine, endOfLine) : "";
return """
--%s%s\
Content-Disposition: form-data; name="title"%s\
%s%s\
%s%s\
--%s%s\
Content-Disposition: form-data; name="description"%s\
%s%s\
%s%s\
--%s--%s""".formatted(
boundary, endOfLine,
endOfLine,
titleHeaders, endOfLine,
titleValue, endOfLine,
boundary, endOfLine,
endOfLine,
descriptionHeaders, endOfLine,
descriptionValue, endOfLine,
boundary, endOfLine);
}
private String createMultipartFileUploadBody(String fileField, String fileName,

View File

@ -45,23 +45,25 @@ class TestGraphQLRequestParamUtils {
private static final String OPERATION_NAME = "";
private static final String QUERY =
"query($id: ID!) {\n"
+ " droid(id: $id) {\n"
+ " id\n"
+ " name\n"
+ " friends {\n"
+ " id\n"
+ " name\n"
+ " appearsIn\n"
+ " }\n"
+ " }\n"
+ "}\n";
private static final String QUERY = """
query($id: ID!) {
droid(id: $id) {
id
name
friends {
id
name
appearsIn
}
}
}
""";
private static final String VARIABLES =
"{\n"
+ " \"id\": \"2001\"\n"
+ "}\n";
private static final String VARIABLES = """
{
"id": "2001"
}
""";
private static final String EXPECTED_QUERY_GET_PARAM_VALUE =
"query($id: ID!) { droid(id: $id) { id name friends { id name appearsIn } } }";

View File

@ -164,8 +164,7 @@ public class DataSourceElement extends AbstractTestElement
public static String getConnectionInfo(String poolName) throws SQLException{
Object poolObject =
JMeterContextService.getContext().getVariables().getObject(poolName);
if (poolObject instanceof DataSourceComponentImpl) {
DataSourceComponentImpl pool = (DataSourceComponentImpl) poolObject;
if (poolObject instanceof DataSourceComponentImpl pool) {
return pool.getConnectionInfo();
} else {
return "Object:" + poolName + " is not of expected type '" + DataSourceComponentImpl.class.getName() + "'";
@ -194,8 +193,7 @@ public class DataSourceElement extends AbstractTestElement
if (poolObject == null) {
throw new SQLException("No pool found named: '" + poolName + "', ensure Variable Name matches Variable Name of JDBC Connection Configuration");
} else {
if(poolObject instanceof DataSourceComponentImpl) {
DataSourceComponentImpl pool = (DataSourceComponentImpl) poolObject;
if(poolObject instanceof DataSourceComponentImpl pool) {
return pool.getConnection();
} else {
String errorMsg = "Found object stored under variable:'" + poolName + "' with class:"

View File

@ -307,8 +307,8 @@ public class JMSSampler extends AbstractSampler implements ThreadListener {
if (replyMsg == null) {
res.setResponseMessage("No reply message received");
} else {
if (replyMsg instanceof TextMessage) {
res.setResponseData(((TextMessage) replyMsg).getText(), null);
if (replyMsg instanceof TextMessage textMessage) {
res.setResponseData(textMessage.getText(), null);
} else {
res.setResponseData(replyMsg.toString(), null);
}
@ -355,20 +355,17 @@ public class JMSSampler extends AbstractSampler implements ThreadListener {
private static void extractContent(StringBuilder buffer, StringBuilder propBuffer, Message msg) {
if (msg != null) {
try {
if (msg instanceof TextMessage) {
buffer.append(((TextMessage) msg).getText());
} else if (msg instanceof ObjectMessage) {
ObjectMessage objectMessage = (ObjectMessage) msg;
if (msg instanceof TextMessage textMessage) {
buffer.append(textMessage.getText());
} else if (msg instanceof ObjectMessage objectMessage) {
if (objectMessage.getObject() != null) {
buffer.append(objectMessage.getObject().getClass());
} else {
buffer.append("object is null");
}
} else if (msg instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) msg;
} else if (msg instanceof BytesMessage bytesMessage) {
buffer.append(bytesMessage.getBodyLength() + " bytes received in BytesMessage");
} else if (msg instanceof MapMessage) {
MapMessage mapm = (MapMessage) msg;
} else if (msg instanceof MapMessage mapm) {
@SuppressWarnings("unchecked") // MapNames are Strings
Enumeration<String> enumb = mapm.getMapNames();
while (enumb.hasMoreElements()) {
@ -484,8 +481,8 @@ public class JMSSampler extends AbstractSampler implements ThreadListener {
Object o = getProperty(JMS_PROPERTIES).getObjectValue();
JMSProperties jmsProperties = null;
// Backward compatibility with versions <= 2.10
if (o instanceof Arguments) {
jmsProperties = Utils.convertArgumentsToJmsProperties((Arguments) o);
if (o instanceof Arguments arguments) {
jmsProperties = Utils.convertArgumentsToJmsProperties(arguments);
} else {
jmsProperties = (JMSProperties) o;
}