use of org.apache.commons.cli.avalon.CLOption in project jmeter by apache.
the class JMeter method extractAndSetReportOutputFolder.
/**
* Extract option JMeter#REPORT_OUTPUT_FOLDER_OPT and if defined sets property
* {@link JMeter#JMETER_REPORT_OUTPUT_DIR_PROPERTY} after checking folder can
* be safely written to
* @param parser {@link CLArgsParser}
* @throws IllegalArgumentException
*/
private void extractAndSetReportOutputFolder(CLArgsParser parser) {
CLOption reportOutputFolderOpt = parser.getArgumentById(REPORT_OUTPUT_FOLDER_OPT);
if (reportOutputFolderOpt != null) {
String reportOutputFolder = parser.getArgumentById(REPORT_OUTPUT_FOLDER_OPT).getArgument();
File reportOutputFolderAsFile = new File(reportOutputFolder);
JOrphanUtils.canSafelyWriteToFolder(reportOutputFolderAsFile);
final String reportOutputFolderAbsPath = reportOutputFolderAsFile.getAbsolutePath();
log.info("Setting property '{}' to:'{}'", JMETER_REPORT_OUTPUT_DIR_PROPERTY, reportOutputFolderAbsPath);
JMeterUtils.setProperty(JMETER_REPORT_OUTPUT_DIR_PROPERTY, reportOutputFolderAbsPath);
}
}
use of org.apache.commons.cli.avalon.CLOption in project jmeter by apache.
the class BasicCurlParser method parse.
public Request parse(String commandLine) {
String[] args = translateCommandline(commandLine);
CLArgsParser parser = new CLArgsParser(args, OPTIONS);
String error = parser.getErrorString();
boolean isPostToGet = false;
if (error == null) {
List<CLOption> clOptions = parser.getArguments();
Request request = new Request();
for (CLOption option : clOptions) {
if (option.getDescriptor().getId() == URL_OPT) {
request.setUrl(option.getArgument());
} else if (option.getDescriptor().getId() == COMPRESSED_OPT) {
request.setCompressed(true);
} else if (option.getDescriptor().getId() == HEADER_OPT) {
String nameAndValue = option.getArgument(0);
int indexOfColon = nameAndValue.indexOf(':');
if (indexOfColon >= 0) {
String name = nameAndValue.substring(0, indexOfColon).trim();
String value = nameAndValue.substring(indexOfColon + 1).trim();
request.addHeader(name, value);
} else if (nameAndValue.endsWith(";")) {
request.addHeader(nameAndValue.substring(0, nameAndValue.length() - 1), "");
} else {
LOGGER.warn("Could not parse header argument [{}] as it didn't contain a colon nor ended with a semicolon", nameAndValue);
}
} else if (option.getDescriptor().getId() == METHOD_OPT) {
String value = option.getArgument(0);
request.setMethod(value);
} else if (DATAS_OPT.contains(option.getDescriptor().getId())) {
String value = option.getArgument(0);
String dataOptionName = option.getDescriptor().getName();
if (value == null) {
value = "";
}
value = getPostDataByDifferentOption(value.trim(), dataOptionName);
if ("GET".equals(request.getMethod())) {
request.setMethod("POST");
}
request.setPostData(value);
} else if (FORMS_OPT.contains(option.getDescriptor().getId())) {
String nameAndValue = option.getArgument(0);
int indexOfEqual = nameAndValue.indexOf('=');
String key = nameAndValue.substring(0, indexOfEqual).trim();
String value = nameAndValue.substring(indexOfEqual + 1).trim();
if ("form-string".equals(option.getDescriptor().getName())) {
request.addFormStringData(key, unquote(value));
} else {
if (value.charAt(0) == '@') {
request.addFormData(key, FileArgumentHolder.of(unquote(value.substring(1))));
} else {
request.addFormData(key, StringArgumentHolder.of(unquote(value)));
}
}
request.setMethod("POST");
} else if (option.getDescriptor().getId() == USER_AGENT_OPT) {
request.addHeader("User-Agent", option.getArgument(0));
} else if (option.getDescriptor().getId() == REFERER_OPT) {
request.addHeader("Referer", option.getArgument(0));
} else if (option.getDescriptor().getId() == CONNECT_TIMEOUT_OPT) {
String value = option.getArgument(0);
request.setConnectTimeout(Double.parseDouble(value) * 1000);
} else if (option.getDescriptor().getId() == COOKIE_OPT) {
String value = option.getArgument(0);
if (isValidCookie(value)) {
request.setCookies(value);
} else {
request.setFilepathCookie(value);
}
} else if (option.getDescriptor().getId() == USER_OPT) {
String value = option.getArgument(0);
setAuthUserPasswd(value, request.getUrl(), request.getAuthorization());
} else if (AUTH_OPT.contains(option.getDescriptor().getId())) {
String authOption = option.getDescriptor().getName();
setAuthMechanism(authOption, request.getAuthorization());
} else if (SSL_OPT.contains(option.getDescriptor().getId())) {
request.setCaCert(option.getDescriptor().getName());
} else if (option.getDescriptor().getId() == GET_OPT) {
isPostToGet = true;
} else if (option.getDescriptor().getId() == DNS_OPT) {
String value = option.getArgument(0);
String[] dnsServer = value.split(",");
for (String s : dnsServer) {
request.addDnsServers(s);
}
} else if (option.getDescriptor().getId() == NO_KEEPALIVE_OPT) {
request.setKeepAlive(false);
} else if (option.getDescriptor().getId() == PROXY_OPT) {
String value = option.getArgument(0);
setProxyServer(request, value);
} else if (option.getDescriptor().getId() == PROXY_USER_OPT) {
String value = option.getArgument(0);
setProxyServerUserInfo(request, value);
} else if (option.getDescriptor().getId() == MAX_TIME_OPT) {
String value = option.getArgument(0);
request.setMaxTime(Double.parseDouble(value) * 1000);
} else if (option.getDescriptor().getId() == HEAD_OPT) {
request.setMethod("HEAD");
} else if (option.getDescriptor().getId() == INTERFACE_OPT) {
String value = option.getArgument(0);
request.setInterfaceName(value);
} else if (option.getDescriptor().getId() == DNS_RESOLVER_OPT) {
String value = option.getArgument(0);
request.setDnsResolver(value);
} else if (option.getDescriptor().getId() == LIMIT_RATE_OPT) {
String value = option.getArgument(0);
request.setLimitRate(value);
} else if (option.getDescriptor().getId() == NOPROXY_OPT) {
String value = option.getArgument(0);
request.setNoproxy(value);
} else if (IGNORE_OPTIONS_OPT.contains(option.getDescriptor().getId())) {
request.addOptionsIgnored(option.getDescriptor().getName());
} else if (NOSUPPORT_OPTIONS_OPT.contains(option.getDescriptor().getId())) {
request.addOptionsNoSupport(option.getDescriptor().getName());
} else if (PROPERTIES_OPT.contains(option.getDescriptor().getId())) {
request.addOptionsInProperties("--" + option.getDescriptor().getName() + " is in 'httpsampler.max_redirects(1062 line)'");
} else if (option.getDescriptor().getId() == CLOption.TEXT_ARGUMENT && !"CURL".equalsIgnoreCase(option.getArgument())) {
try {
request.setUrl(new URL(option.getArgument()).toExternalForm());
} catch (MalformedURLException ex) {
LOGGER.warn("Unhandled option {}", option.getArgument());
}
}
}
if (isPostToGet) {
String url = request.getUrl() + "?" + request.getPostData();
request.setUrl(url);
request.setPostData(null);
request.setMethod("GET");
}
return request;
} else {
throw new IllegalArgumentException("Unexpected format for command line:" + commandLine + ", error:" + error);
}
}
use of org.apache.commons.cli.avalon.CLOption in project jmeter by apache.
the class HttpMirrorServer method setLogLevel.
private static void setLogLevel(CLArgsParser parser) {
CLOption logLevelOption = parser.getArgumentById(LOGLEVEL_OPT_ID);
if (logLevelOption == null) {
return;
}
String name = logLevelOption.getArgument(0);
final Level logLevel = Level.getLevel(name);
if (logLevel == null) {
getLogger().warn("Invalid log level '{}'.", name);
return;
}
String value = logLevelOption.getArgument(1);
if (StringUtils.isEmpty(value)) {
// Set root level
// $NON-NLS-1$
getLogger().info("Setting root log level to '{}'", name);
Configurator.setRootLevel(logLevel);
} else {
// Set category
String loggerName = name;
if (name.startsWith("jmeter") || name.startsWith("jorphan")) {
// $NON-NLS-1$
loggerName = "org.apache." + name;
}
// $NON-NLS-1$
getLogger().info("Setting log level to '{}' for '{}'.", value, loggerName);
Configurator.setAllLevels(loggerName, logLevel);
}
}
use of org.apache.commons.cli.avalon.CLOption in project jmeter by apache.
the class JMeter method start.
/**
* Takes the command line arguments and uses them to determine how to
* startup JMeter.
*
* Called reflectively by {@link NewDriver#main(String[])}
* @param args The arguments for JMeter
*/
@SuppressWarnings("JdkObsolete")
public void start(String[] args) {
CLArgsParser parser = new CLArgsParser(args, options);
String error = parser.getErrorString();
if (error == null) {
// Check option combinations
boolean gui = parser.getArgumentById(NONGUI_OPT) == null;
boolean nonGuiOnly = parser.getArgumentById(REMOTE_OPT) != null || parser.getArgumentById(REMOTE_OPT_PARAM) != null || parser.getArgumentById(REMOTE_STOP) != null;
if (gui && nonGuiOnly) {
error = "-r and -R and -X are only valid in non-GUI mode";
}
}
if (null != error) {
// NOSONAR
System.err.println("Error: " + error);
// NOSONAR
System.out.println("Usage");
// NOSONAR
System.out.println(CLUtil.describeOptions(options).toString());
// repeat the error so no need to scroll back past the usage to see it
// NOSONAR
System.out.println("Error: " + error);
return;
}
try {
// Also initialises JMeter logging
initializeProperties(parser);
SecurityProviderLoader.addSecurityProvider(JMeterUtils.getJMeterProperties());
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
if (!(e instanceof ThreadDeath)) {
log.error("Uncaught exception in thread {}", t, e);
// NOSONAR
System.err.println("Uncaught Exception " + e + " in thread " + t + ". See log file for details.");
}
});
if (log.isInfoEnabled()) {
log.info(JMeterUtils.getJMeterCopyright());
log.info("Version {}", JMeterUtils.getJMeterVersion());
// $NON-NLS-1$ //$NON-NLS-2$
log.info("java.version={}", System.getProperty("java.version"));
// $NON-NLS-1$ //$NON-NLS-2$
log.info("java.vm.name={}", System.getProperty("java.vm.name"));
// $NON-NLS-1$ //$NON-NLS-2$
log.info("os.name={}", System.getProperty("os.name"));
// $NON-NLS-1$ //$NON-NLS-2$
log.info("os.arch={}", System.getProperty("os.arch"));
// $NON-NLS-1$ //$NON-NLS-2$
log.info("os.version={}", System.getProperty("os.version"));
// $NON-NLS-1$ //$NON-NLS-2$
log.info("file.encoding={}", System.getProperty("file.encoding"));
// $NON-NLS-1$ //$NON-NLS-2$
log.info("java.awt.headless={}", System.getProperty("java.awt.headless"));
log.info("Max memory ={}", Runtime.getRuntime().maxMemory());
log.info("Available Processors ={}", Runtime.getRuntime().availableProcessors());
log.info("Default Locale={}", Locale.getDefault().getDisplayName());
log.info("JMeter Locale={}", JMeterUtils.getLocale().getDisplayName());
log.info("JMeterHome={}", JMeterUtils.getJMeterHome());
// $NON-NLS-1$ //$NON-NLS-2$
log.info("user.dir ={}", System.getProperty("user.dir"));
// $NON-NLS-1$
log.info("PWD ={}", new File(".").getCanonicalPath());
log.info("IP: {} Name: {} FullName: {}", JMeterUtils.getLocalHostIP(), JMeterUtils.getLocalHostName(), JMeterUtils.getLocalHostFullName());
}
setProxy(parser);
updateClassLoader();
if (log.isDebugEnabled()) {
// $NON-NLS-1$
String jcp = System.getProperty("java.class.path");
String[] bits = jcp.split(File.pathSeparator);
log.debug("ClassPath");
for (String bit : bits) {
log.debug(bit);
}
}
// Set some (hopefully!) useful properties
long now = System.currentTimeMillis();
// $NON-NLS-1$
JMeterUtils.setProperty("START.MS", Long.toString(now));
// so it agrees with above
Date today = new Date(now);
// $NON-NLS-1$ $NON-NLS-2$
JMeterUtils.setProperty("START.YMD", new SimpleDateFormat("yyyyMMdd").format(today));
// $NON-NLS-1$ $NON-NLS-2$
JMeterUtils.setProperty("START.HMS", new SimpleDateFormat("HHmmss").format(today));
if (parser.getArgumentById(VERSION_OPT) != null) {
displayAsciiArt();
} else if (parser.getArgumentById(HELP_OPT) != null) {
displayAsciiArt();
// NOSONAR $NON-NLS-1$
System.out.println(JMeterUtils.getResourceFileAsText("org/apache/jmeter/help.txt"));
} else if (parser.getArgumentById(OPTIONS_OPT) != null) {
displayAsciiArt();
// NOSONAR
System.out.println(CLUtil.describeOptions(options).toString());
} else if (parser.getArgumentById(SERVER_OPT) != null) {
// Start the server
try {
// $NON-NLS-1$
RemoteJMeterEngineImpl.startServer(RmiUtils.getRmiRegistryPort());
startOptionalServers();
} catch (Exception ex) {
// NOSONAR
System.err.println("Server failed to start: " + ex);
log.error("Giving up, as server failed with:", ex);
throw ex;
}
} else {
String testFile = null;
CLOption testFileOpt = parser.getArgumentById(TESTFILE_OPT);
if (testFileOpt != null) {
testFile = testFileOpt.getArgument();
if (USE_LAST_JMX.equals(testFile)) {
// most recent
testFile = LoadRecentProject.getRecentFile(0);
}
}
CLOption testReportOpt = parser.getArgumentById(REPORT_GENERATING_OPT);
if (testReportOpt != null) {
// generate report from existing file
String reportFile = testReportOpt.getArgument();
extractAndSetReportOutputFolder(parser, deleteResultFile);
ReportGenerator generator = new ReportGenerator(reportFile, null);
generator.generate();
} else if (parser.getArgumentById(NONGUI_OPT) == null) {
// not non-GUI => GUI
String initialTestFile = testFile;
SwingUtilities.invokeAndWait(() -> startGui(initialTestFile));
startOptionalServers();
} else {
// NON-GUI must be true
extractAndSetReportOutputFolder(parser, deleteResultFile);
CLOption remoteTest = parser.getArgumentById(REMOTE_OPT_PARAM);
if (remoteTest == null) {
remoteTest = parser.getArgumentById(REMOTE_OPT);
}
CLOption jtl = parser.getArgumentById(LOGFILE_OPT);
String jtlFile = null;
if (jtl != null) {
// $NON-NLS-1$
jtlFile = processLAST(jtl.getArgument(), ".jtl");
}
CLOption reportAtEndOpt = parser.getArgumentById(REPORT_AT_END_OPT);
if (reportAtEndOpt != null && jtlFile == null) {
throw new IllegalUserActionException("Option -" + ((char) REPORT_AT_END_OPT) + " requires -" + ((char) LOGFILE_OPT) + " option");
}
startNonGui(testFile, jtlFile, remoteTest, reportAtEndOpt != null);
startOptionalServers();
}
}
} catch (IllegalUserActionException e) {
// NOSONAR
// NOSONAR
System.out.println("Incorrect Usage:" + e.getMessage());
// NOSONAR
System.out.println(CLUtil.describeOptions(options).toString());
} catch (Throwable e) {
// NOSONAR
log.error("An error occurred: ", e);
// NOSONAR
System.out.println("An error occurred: " + e.getMessage());
// FIXME Should we exit here ? If we are called by Maven or Jenkins
System.exit(1);
}
}
use of org.apache.commons.cli.avalon.CLOption in project jmeter by apache.
the class JMeter method initializeProperties.
private void initializeProperties(CLArgsParser parser) {
if (parser.getArgumentById(PROPFILE_OPT) != null) {
JMeterUtils.loadJMeterProperties(parser.getArgumentById(PROPFILE_OPT).getArgument());
} else {
JMeterUtils.loadJMeterProperties(NewDriver.getJMeterDir() + File.separator + "bin" + // $NON-NLS-1$
File.separator + // $NON-NLS-1$
"jmeter.properties");
}
JMeterUtils.initLocale();
// Bug 33845 - allow direct override of Home dir
if (parser.getArgumentById(JMETER_HOME_OPT) == null) {
JMeterUtils.setJMeterHome(NewDriver.getJMeterDir());
} else {
JMeterUtils.setJMeterHome(parser.getArgumentById(JMETER_HOME_OPT).getArgument());
}
Properties jmeterProps = JMeterUtils.getJMeterProperties();
remoteProps = new Properties();
// Add local JMeter properties, if the file is found
// $NON-NLS-1$
String userProp = JMeterUtils.getPropDefault("user.properties", "");
if (userProp.length() > 0) {
// $NON-NLS-1$
File file = JMeterUtils.findFile(userProp);
if (file.canRead()) {
try (FileInputStream fis = new FileInputStream(file)) {
log.info("Loading user properties from: {}", file);
Properties tmp = new Properties();
tmp.load(fis);
jmeterProps.putAll(tmp);
} catch (IOException e) {
log.warn("Error loading user property file: {}", userProp, e);
}
}
}
// Add local system properties, if the file is found
// $NON-NLS-1$
String sysProp = JMeterUtils.getPropDefault("system.properties", "");
if (sysProp.length() > 0) {
File file = JMeterUtils.findFile(sysProp);
if (file.canRead()) {
try (FileInputStream fis = new FileInputStream(file)) {
log.info("Loading system properties from: {}", file);
System.getProperties().load(fis);
} catch (IOException e) {
log.warn("Error loading system property file: {}", sysProp, e);
}
}
}
// Process command line property definitions
// These can potentially occur multiple times
List<CLOption> clOptions = parser.getArguments();
for (CLOption option : clOptions) {
String name = option.getArgument(0);
String value = option.getArgument(1);
switch(option.getDescriptor().getId()) {
// Should not have any text arguments
case CLOption.TEXT_ARGUMENT:
throw new IllegalArgumentException("Unknown arg: " + option.getArgument());
case // Bug 33920 - allow multiple props
PROPFILE2_OPT:
log.info("Loading additional properties from: {}", name);
try (FileInputStream fis = new FileInputStream(new File(name))) {
Properties tmp = new Properties();
tmp.load(fis);
jmeterProps.putAll(tmp);
} catch (FileNotFoundException e) {
// NOSONAR
log.warn("Can't find additional property file: {}", name, e);
} catch (IOException e) {
// NOSONAR
log.warn("Error loading additional property file: {}", name, e);
}
break;
case SYSTEM_PROPFILE:
log.info("Setting System properties from file: {}", name);
try (FileInputStream fis = new FileInputStream(new File(name))) {
System.getProperties().load(fis);
} catch (IOException e) {
// NOSONAR
if (log.isWarnEnabled()) {
log.warn("Cannot find system property file. {}", e.getLocalizedMessage());
}
}
break;
case SYSTEM_PROPERTY:
if (value.length() > 0) {
// Set it
log.info("Setting System property: {}={}", name, value);
System.getProperties().setProperty(name, value);
} else {
// Reset it
log.warn("Removing System property: {}", name);
System.getProperties().remove(name);
}
break;
case JMETER_PROPERTY:
if (value.length() > 0) {
// Set it
log.info("Setting JMeter property: {}={}", name, value);
jmeterProps.setProperty(name, value);
} else {
// Reset it
log.warn("Removing JMeter property: {}", name);
jmeterProps.remove(name);
}
break;
case JMETER_GLOBAL_PROP:
if (value.length() > 0) {
// Set it
log.info("Setting Global property: {}={}", name, value);
remoteProps.setProperty(name, value);
} else {
File propFile = new File(name);
if (propFile.canRead()) {
log.info("Setting Global properties from the file {}", name);
try (FileInputStream fis = new FileInputStream(propFile)) {
remoteProps.load(fis);
} catch (FileNotFoundException e) {
// NOSONAR
if (log.isWarnEnabled()) {
log.warn("Could not find properties file: {}", e.getLocalizedMessage());
}
} catch (IOException e) {
// NOSONAR
if (log.isWarnEnabled()) {
log.warn("Could not load properties file: {}", e.getLocalizedMessage());
}
}
}
}
break;
case LOGLEVEL:
if (value.length() > 0) {
// Set category
log.info("LogLevel: {}={}", name, value);
final Level logLevel = Level.getLevel(value);
if (logLevel != null) {
String loggerName = name;
if (name.startsWith("jmeter") || name.startsWith("jorphan")) {
loggerName = PACKAGE_PREFIX + name;
}
Configurator.setAllLevels(loggerName, logLevel);
} else {
log.warn("Invalid log level, '{}' for '{}'.", value, name);
}
} else {
// Set root level
log.warn("LogLevel: {}", name);
final Level logLevel = Level.getLevel(name);
if (logLevel != null) {
Configurator.setRootLevel(logLevel);
} else {
log.warn("Invalid log level, '{}', for the root logger.", name);
}
}
break;
case REMOTE_STOP:
remoteStop = true;
break;
case FORCE_DELETE_RESULT_FILE:
deleteResultFile = true;
break;
default:
// ignored
break;
}
}
String sampleVariables = (String) jmeterProps.get(SampleEvent.SAMPLE_VARIABLES);
if (sampleVariables != null) {
remoteProps.put(SampleEvent.SAMPLE_VARIABLES, sampleVariables);
}
jmeterProps.put("jmeter.version", JMeterUtils.getJMeterVersion());
}
Aggregations