Java Code Examples for org.apache.jmeter.util.JMeterUtils

The following examples show how to use org.apache.jmeter.util.JMeterUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jmeter-plugins-webdriver   Source File: WebDriverSampler.java    License: Apache License 2.0 6 votes vote down vote up
ScriptEngine createScriptEngineWith(SampleResult sampleResult) {
    final ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(this.getScriptLanguage());
    Bindings engineBindings = new SimpleBindings();
    WebDriverScriptable scriptable = new WebDriverScriptable();
    scriptable.setName(getName());
    scriptable.setParameters(getParameters());
    JMeterContext context = JMeterContextService.getContext();
    scriptable.setVars(context.getVariables());
    scriptable.setProps(JMeterUtils.getJMeterProperties());
    scriptable.setCtx(context);
    scriptable.setLog(LOGGER);
    scriptable.setSampleResult(sampleResult);
    scriptable.setBrowser(getWebDriver());
    engineBindings.put("WDS", scriptable);
    scriptEngine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
    return scriptEngine;
}
 
Example 2
Source Project: jmeter-bzm-plugins   Source File: BlazemeterUploaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFlow() throws Exception {
    JMeterUtils.setProperty("blazemeter.client", BLCEmul.class.getName());
    BlazeMeterUploader uploader = new BlazeMeterUploader();
    uploader.setGui(new BlazeMeterUploaderGui());
    uploader.setShareTest(true);
    uploader.setProject("project");
    uploader.setTitle("title");
    uploader.testStarted();
    uploader.testEnded();

    assertEquals(true, uploader.isShareTest());
    assertEquals("project", uploader.getProject());
    assertEquals("title", uploader.getTitle());
    assertEquals("", uploader.getUploadToken());
}
 
Example 3
@Test
public void testTestEndedWithNoStoreDir() throws IOException {
    System.out.println("testEnded");
    JMeterUtils.setProperty("loadosophia.address", "http://localhost/");
    LoadosophiaUploader instance = new LoadosophiaUploaderEmul();
    instance.setStoreDir("");
    instance.setTitle("UnitTest");
    instance.setColorFlag("gray");
    instance.setProject("DEFAULT");
    instance.setUploadToken("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
    instance.testStarted();

    SampleResult res = new SampleResult();
    res.sampleStart();
    res.sampleEnd();
    SampleEvent event = new SampleEvent(res, "test");
    instance.sampleOccurred(event);

    instance.testEnded();
}
 
Example 4
Source Project: jmeter-plugins   Source File: AbstractSimpleThreadGroup.java    License: Apache License 2.0 6 votes vote down vote up
private JMeterThread makeThread(int groupNum,
                                ListenerNotifier notifier, ListedHashTree threadGroupTree,
                                StandardJMeterEngine engine, int threadNum,
                                JMeterContext context) { // N.B. Context needs to be fetched in the correct thread
    boolean onErrorStopTest = getOnErrorStopTest();
    boolean onErrorStopTestNow = getOnErrorStopTestNow();
    boolean onErrorStopThread = getOnErrorStopThread();
    boolean onErrorStartNextLoop = getOnErrorStartNextLoop();

    String groupName = getName();
    String distributedPrefix = JMeterUtils.getPropDefault(THREAD_GROUP_DISTRIBUTED_PREFIX_PROPERTY_NAME, "");
    final String threadName = distributedPrefix + (distributedPrefix.isEmpty() ? "" : "-") + groupName + " " + groupNum + "-" + (threadNum + 1);

    final JMeterThread jmeterThread = new JMeterThread(cloneTree(threadGroupTree), this, notifier);
    jmeterThread.setThreadNum(threadNum);
    jmeterThread.setThreadGroup(this);
    jmeterThread.setInitialContext(context);
    jmeterThread.setThreadName(threadName);
    jmeterThread.setEngine(engine);
    jmeterThread.setOnErrorStopTest(onErrorStopTest);
    jmeterThread.setOnErrorStopTestNow(onErrorStopTestNow);
    jmeterThread.setOnErrorStopThread(onErrorStopThread);
    jmeterThread.setOnErrorStartNextLoop(onErrorStartNextLoop);
    return jmeterThread;
}
 
Example 5
Source Project: jsflight   Source File: JMeterProxyControl.java    License: Apache License 2.0 6 votes vote down vote up
private boolean matchesPatterns(String url, CollectionProperty patterns)
{
    for (JMeterProperty jMeterProperty : patterns)
    {
        String item = jMeterProperty.getStringValue();
        try
        {
            Pattern pattern = JMeterUtils.getPatternCache().getPattern(item,
                    Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.SINGLELINE_MASK);
            if (JMeterUtils.getMatcher().matches(url, pattern))
            {
                return true;
            }
        }
        catch (MalformedCachePatternException e)
        {
            LOG.warn("Skipped invalid pattern: " + item, e);
        }
    }
    return false;
}
 
Example 6
Source Project: jmeter-plugins   Source File: VariableThroughputTimer.java    License: Apache License 2.0 6 votes vote down vote up
private void trySettingLoadFromProperty() {
    String loadProp = JMeterUtils.getProperty(DATA_PROPERTY);
    log.debug("Loading property: {}={}", DATA_PROPERTY, loadProp);
    if (!StringUtils.isEmpty(loadProp)) {
        log.info("GUI load profile will be ignored as property {} is defined", DATA_PROPERTY);
        PowerTableModel dataModel = new PowerTableModel(VariableThroughputTimer.columnIdentifiers, VariableThroughputTimer.columnClasses);

        String[] chunks = loadProp.split("\\)");

        for (String chunk : chunks) {
            try {
                parseChunk(chunk, dataModel);
            } catch (RuntimeException e) {
                log.warn("Wrong load chunk {} will be ignored", chunk, e);
            }
        }

        log.info("Setting load profile from property {}: {}", DATA_PROPERTY, loadProp);
        overrideProp = JMeterPluginsUtils.tableModelRowsToCollectionProperty(dataModel, VariableThroughputTimer.DATA_PROPERTY);
    }
}
 
Example 7
Source Project: jmeter-plugins   Source File: DummySamplerGuiTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void displayGUI() throws InterruptedException {
    if (!GraphicsEnvironment.isHeadless()) {
        JMeterUtils.setProperty("search_paths", System.getProperty("user.home") + "/.m2/repository/org/apache/jmeter/ApacheJMeter_core/2.13");

        DummySamplerGui obj = new DummySamplerGui();
        DummySampler te = (DummySampler) obj.createTestElement();
        obj.configure(te);
        obj.clearGui();
        obj.modifyTestElement(te);

        JFrame frame = new JFrame(obj.getStaticLabel());

        frame.setPreferredSize(new Dimension(1024, 768));
        frame.getContentPane().add(obj, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

        while (frame.isVisible()) {
            Thread.sleep(1000);
        }
    }
}
 
Example 8
Source Project: jmeter-plugins   Source File: JMeterPluginsUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String getShortHostname(String host) {
    log.debug("getShortHostname: " + host);
    try {
        String defaultRegex = "([\\w\\-]+)\\..*";
        String hostnameRegex = JMeterUtils.getPropDefault("jmeterPlugin.perfmon.label.useHostname.pattern", defaultRegex);
        log.debug("hostnameRegex: " + hostnameRegex);
        Pattern p = Pattern.compile(hostnameRegex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(host);
        if (m.matches()) {
            String shortName = m.group(1);
            log.debug("shortName of " + host + " is: " + shortName);
            host = shortName;
        }
    } catch (Exception e) {
        log.warn("getShortHostname exception: " + e.getClass().getName() + " :: " + e.getMessage());
        log.debug("getShortHostname exception: ", e);
    }
    return host;
}
 
Example 9
Source Project: jmeter-plugins   Source File: GraphModelToCsvExporter.java    License: Apache License 2.0 6 votes vote down vote up
public GraphModelToCsvExporter(
        AbstractMap<String, AbstractGraphRow> rows,
        File destFile,
        String csvSeparator,
        String xAxisLabel,
        NumberRenderer xAxisRenderer,
        int hideNonRepValLimit) {
    this.destFile = destFile;
    this.model = rows;
    this.csvSeparator = csvSeparator;
    this.decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
    this.xAxisLabel = xAxisLabel;
    this.hideNonRepValLimit = hideNonRepValLimit;
    if (xAxisRenderer != null && xAxisRenderer instanceof DividerRenderer) {
        this.xAxisRenderer = new DividerRenderer(((DividerRenderer) xAxisRenderer).getFactor());
    } else if (xAxisRenderer != null && xAxisRenderer instanceof DateTimeRenderer) {
        String format = JMeterUtils.getPropDefault("jmeterPlugin.csvTimeFormat", "HH:mm:ss" + decimalSeparator + "S");
        dateFormatter = new SimpleDateFormat(format);
    }
}
 
Example 10
Source Project: jmeter-plugins   Source File: JMeterPluginsUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetShortHostnameCustomPattern1() throws IOException {
    System.out.println("testGetShortHostnameCustomPattern1");
    TestJMeterUtils.createJmeterEnv();
    JMeterUtils.setProperty("jmeterPlugin.perfmon.label.useHostname.pattern", "([\\w\\-]+\\.us-(east|west)-[0-9]).*");
    String host;
    host = JMeterPluginsUtils.getShortHostname("host1.us-west-2.ec2.internal");
    assertEquals("host1.us-west-2", host);
    host = JMeterPluginsUtils.getShortHostname("host.us-west-2.ec2.internal");
    assertEquals("host.us-west-2", host);
    host = JMeterPluginsUtils.getShortHostname("1host.us-east-1.ec2.internal");
    assertEquals("1host.us-east-1", host);
    host = JMeterPluginsUtils.getShortHostname("search-head.us-west-1.ec2.internal");
    assertEquals("search-head.us-west-1", host);
    host = JMeterPluginsUtils.getShortHostname("search-index.us-west-2.ec2.internal");
    assertEquals("search-index.us-west-2", host);
}
 
Example 11
Source Project: jmeter-plugins   Source File: AutoStop.java    License: Apache License 2.0 6 votes vote down vote up
private void stopTestViaUDP(String command) {
    try {
        int port = JMeterUtils.getPropDefault("jmeterengine.nongui.port", JMeter.UDP_PORT_DEFAULT);
        log.info("Sending " + command + " request to port " + port);
        DatagramSocket socket = new DatagramSocket();
        byte[] buf = command.getBytes("ASCII");
        InetAddress address = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);
        socket.send(packet);
        socket.close();
    } catch (Exception e) {
        //e.printStackTrace();
        log.error(e.getMessage());
    }

}
 
Example 12
Source Project: jmeter-plugins   Source File: AbstractThreadStarter.java    License: Apache License 2.0 6 votes vote down vote up
protected DynamicThread makeThread(long threadIndex) {
    boolean onErrorStopTest = owner.getOnErrorStopTest();
    boolean onErrorStopTestNow = owner.getOnErrorStopTestNow();
    boolean onErrorStopThread = owner.getOnErrorStopThread();
    boolean onErrorStartNextLoop = owner.getOnErrorStartNextLoop();
    final DynamicThread jmeterThread = new DynamicThread(treeClone, this.owner, notifier);
    jmeterThread.setThreadNum((int) threadIndex);
    jmeterThread.setThreadGroup(this.owner);
    jmeterThread.setInitialContext(context);
    String groupName = getName();
    String distributedPrefix = JMeterUtils.getPropDefault(AbstractSimpleThreadGroup.THREAD_GROUP_DISTRIBUTED_PREFIX_PROPERTY_NAME, "");
    final String threadName = distributedPrefix + (distributedPrefix.isEmpty() ? "" : "-") + groupName + " " + groupIndex + "-" + (threadIndex + 1);
    jmeterThread.setThreadName(threadName);
    jmeterThread.setEngine(engine);
    jmeterThread.setOnErrorStopTest(onErrorStopTest);
    jmeterThread.setOnErrorStopTestNow(onErrorStopTestNow);
    jmeterThread.setOnErrorStopThread(onErrorStopThread);
    jmeterThread.setOnErrorStartNextLoop(onErrorStartNextLoop);
    return jmeterThread;
}
 
Example 13
Source Project: jmeter-plugins-webdriver   Source File: WebDriverSampler.java    License: Apache License 2.0 5 votes vote down vote up
public WebDriverSampler() {
    Class<SampleResult> srClass;
    this.scriptEngineManager = new ScriptEngineManager();
    String className = JMeterUtils.getPropDefault("webdriver.sampleresult_class", SampleResult.class.getCanonicalName());
    try {
        srClass = (Class<SampleResult>) Class.forName(className);
    } catch (ClassNotFoundException e) {
        LOGGER.warn("Class " + className + " not found, defaulted to " + SampleResult.class.getCanonicalName(), e);
        srClass = SampleResult.class;
    }
    sampleResultClass = srClass;
}
 
Example 14
@BeforeClass
public static void setUp() throws Exception {
    TestJMeterUtils.createJmeterEnv();
    JMeterUtils.setProperty("HTTPResponse.parsers", "htmlParser");
    JMeterUtils.setProperty("htmlParser.types", "text/html");
    JMeterUtils.setProperty("htmlParser.className", "org.apache.jmeter.protocol.http.parser.LagartoBasedHtmlParser");
}
 
Example 15
@BeforeClass
  public static void setUpClass()
          throws Exception {
TestJMeterUtils.createJmeterEnv();
factoryMock = Mockito.mock(Factory.class);
handlerMqttMock = Mockito.mock(MqttCallBackImpl.class);
mqttAsyncClientMock = Mockito.mock(IMqttAsyncClient.class);
JMeterUtils.setProperty("WebSocketConnectionConfig.Server", "server");
  }
 
Example 16
Source Project: jmeter-bzm-plugins   Source File: JMeterXMPPConnection.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, AbstractXMPPAction> getAvailableActions() {
    Map<String, AbstractXMPPAction> actions = new TreeMap<>(new OrderComparator());

    try {
        for (String cls : JMeterUtils.findClassesThatExtend(AbstractXMPPAction.class)) {
            actions.put(cls, (AbstractXMPPAction) Class.forName(cls).newInstance());
        }
    } catch (IOException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        log.error("Error loading actions", e);
    }

    return actions;
}
 
Example 17
private void setSearchPaths() {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    String classes = ".";
    for (URL url : urls) {
        if (url.getFile().contains("bouncy") || !url.getFile().contains("jmeter")) {
            continue;
        }

        classes += ";" + url.getFile();
    }
    JMeterUtils.setProperty("search_paths", classes);
}
 
Example 18
Source Project: jmeter-prometheus-plugin   Source File: ListenerGuiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void simpleTest() {
	JMeterUtils.setLocale(Locale.ENGLISH);
	
	PrometheusListenerGui gui = new PrometheusListenerGui();
	
	String comment = "this should be the comment";
	String name = "simple listener name";
	
	gui.setName(name);
	gui.setComment(comment);
	
	Assert.assertEquals(name, gui.getName());
	Assert.assertEquals(comment, gui.getComment());
}
 
Example 19
Source Project: jmeter-prometheus-plugin   Source File: ConfigGuiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void simpleTest() {
	JMeterUtils.setLocale(Locale.ENGLISH);
	
	PrometheusMetricsConfigGui<BaseCollectorConfig> gui = new PrometheusMetricsConfigGui<>();
	
	String comment = "this should be the comment";
	String name = "simple cfg name";
	
	gui.setName(name);
	gui.setComment(comment);
	
	Assert.assertEquals(name, gui.getName());
	Assert.assertEquals(comment, gui.getComment());
}
 
Example 20
Source Project: jmeter-prometheus-plugin   Source File: TestUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public static void createJmeterEnv() {
  	
      JMeterUtils.setJMeterHome("src/test/resources");
      JMeterUtils.setLocale(Locale.ENGLISH);
      JMeterUtils.loadJMeterProperties("src/test/resources/bin/jmeter.properties");
      
      try {
	SaveService.loadProperties();
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

      JMeterTreeModel jMeterTreeModel = new JMeterTreeModel();
      JMeterTreeListener jMeterTreeListener = new JMeterTreeListener();
      jMeterTreeListener.setModel(jMeterTreeModel);
      
      JMeterContextService.getContext().setVariables(new JMeterVariables());
      StandardJMeterEngine engine = new StandardJMeterEngine();
      JMeterContextService.getContext().setEngine(engine);
      
      JMeterThreadMonitor monitor = new NOOPThreadMonitor();
      
      
      HashTree hashtree = new HashTree();
      hashtree.add(new LoopController());
      
      JMeterThread thread = new JMeterThread(hashtree, monitor, null);
      thread.setThreadName("test thread");
      JMeterContextService.getContext().setThread(thread);
      
      
      ThreadGroup tg1 = new ThreadGroup();
      tg1.setName("tg1");
      JMeterContextService.getContext().setThreadGroup(tg1);
      
  }
 
Example 21
Source Project: jmeter-debugger   Source File: DebuggerDialog.java    License: Apache License 2.0 5 votes vote down vote up
private void refreshProperties() {
    propsTableModel.clearData();
    for (Map.Entry<Object, Object> var : JMeterUtils.getJMeterProperties().entrySet()) {
        propsTableModel.addRow(new String[]{var.getKey().toString(), var.getValue().toString()});
    }
    propsTableModel.fireTableDataChanged();
}
 
Example 22
Source Project: jmeter-debugger   Source File: DebuggerDialogTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGui() throws Exception {
    if (GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance()) {
        return;
    }
    String actions = ActionRouter.class.getProtectionDomain().getCodeSource().getLocation().getFile();
    String renderers = RenderAsHTML.class.getProtectionDomain().getCodeSource().getLocation().getFile();
    JMeterUtils.setProperty("search_paths", actions + ";" + renderers);
    TestProvider prov = new TestProvider();
    JMeterTreeModel mdl = prov.getTreeModel();
    JMeterTreeListener a = new JMeterTreeListener();
    a.setActionHandler(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            log.debug("Action " + actionEvent);
        }
    });
    a.setModel(mdl);
    GuiPackage.getInstance(a, mdl);

    DebuggerDialog obj = new DebuggerDialogMock(prov.getTreeModel());
    obj.componentShown(null);
    obj.started();
    obj.statusRefresh(JMeterContextService.getContext());
    obj.frozenAt(new SamplerDebug());
    obj.continuing();
    obj.stopped();
    obj.componentHidden(null);
}
 
Example 23
Source Project: jsflight   Source File: JMeterProxyControl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if matching pattern was different from expectedToMatch
 *
 * @param expression        Expression to match
 * @param sampleContentType
 * @return boolean true if Matching expression
 */
private boolean testPattern(String expression, String sampleContentType, boolean expectedToMatch)
{
    if (expression != null && expression.length() > 0)
    {
        if (LOG.isDebugEnabled())
        {
            LOG.debug("Testing Expression : " + expression + " on sampleContentType:" + sampleContentType
                    + ", expected to match:" + expectedToMatch);
        }

        Pattern pattern;
        try
        {
            pattern = JMeterUtils.getPatternCache().getPattern(expression,
                    Perl5Compiler.READ_ONLY_MASK | Perl5Compiler.SINGLELINE_MASK);
            if (JMeterUtils.getMatcher().contains(sampleContentType, pattern) != expectedToMatch)
            {
                return false;
            }
        }
        catch (MalformedCachePatternException e)
        {
            LOG.warn("Skipped invalid content pattern: " + expression, e);
        }
    }
    return true;
}
 
Example 24
Source Project: jsflight   Source File: JMeterProxyControl.java    License: Apache License 2.0 5 votes vote down vote up
private void placeSampler(final HTTPSamplerBase sampler, final TestElement[] subConfigs, final TestElement myTarget)
{
    try
    {
        JMeterUtils.runSafe(() -> myTarget.addTestElement(sampler));
    }
    catch (Exception e)
    {
        JMeterUtils.reportErrorToUser(e.getMessage());
    }
}
 
Example 25
Source Project: jsflight   Source File: JMeterProxyControl.java    License: Apache License 2.0 5 votes vote down vote up
private void initKeyStore() throws IOException, GeneralSecurityException
{
    switch (KEYSTORE_MODE)
    {
    case DYNAMIC_KEYSTORE:
        storePassword = getPassword();
        keyPassword = getPassword();
        initDynamicKeyStore();
        break;
    case JMETER_KEYSTORE:
        storePassword = getPassword();
        keyPassword = getPassword();
        initJMeterKeyStore();
        break;
    case USER_KEYSTORE:
        storePassword = JMeterUtils.getPropDefault("proxy.cert.keystorepass", DEFAULT_PASSWORD); // $NON-NLS-1$;
        keyPassword = JMeterUtils.getPropDefault("proxy.cert.keypassword", DEFAULT_PASSWORD); // $NON-NLS-1$;
        LOG.info("HTTP(S) Test Script Recorder will use the keystore '" + CERT_PATH_ABS + "' with the alias: '"
                + CERT_ALIAS + "'");
        initUserKeyStore();
        break;
    case NONE:
        throw new IOException("Cannot find keytool application and no keystore was provided");
    default:
        throw new IllegalStateException("Impossible case: " + KEYSTORE_MODE);
    }
}
 
Example 26
Source Project: teammates   Source File: BaseLNPTestCase.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Setup and load the JMeter configuration and property files to run the Jmeter test.
 * @throws IOException if the save service properties file cannot be loaded.
 */
private void setJmeterProperties() throws IOException {
    JMeterUtils.loadJMeterProperties(TestProperties.JMETER_PROPERTIES_PATH);
    JMeterUtils.setJMeterHome(TestProperties.JMETER_HOME);
    JMeterUtils.initLocale();
    SaveService.loadProperties();
}
 
Example 27
Source Project: kafkameter   Source File: LoadGeneratorBeanInfo.java    License: Apache License 2.0 5 votes vote down vote up
private static List<String> findAvailableImplementations() {
  try {
    return ClassFinder.findClassesThatExtend(
        JMeterUtils.getSearchPaths(), new Class[] { SyntheticLoadGenerator.class });
  } catch (IOException e) {
    log.fatalError("Exception finding SyntheticLoadGenerator implementations", e);
    throw Throwables.propagate(e);
  }
}
 
Example 28
Source Project: jmeter-plugins   Source File: AbstractIPSampler.java    License: Apache License 2.0 5 votes vote down vote up
public AbstractIPSampler() {
    //recvBuf = ByteBuffer.allocateDirect(JMeterUtils.getPropDefault(RECV_BUFFER_LEN_PROPERTY, 1024 * 4));
    recvDataLimit = JMeterUtils.getPropDefault(RESULT_DATA_LIMIT, Integer.MAX_VALUE);
    if (recvDataLimit < Integer.MAX_VALUE) {
        log.info("Limiting result data to " + recvDataLimit);
    }
}
 
Example 29
Source Project: jmeter-plugins   Source File: TestJMeterUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void createJmeterEnv() {
    JMeterUtils.setJMeterHome(getTempDir());

    File dst = new File(JMeterUtils.getJMeterHome() + "/ss.props");
    InputStream src = DirectoryAnchor.class.getResourceAsStream("/kg/apc/jmeter/bin/saveservice.properties");
    try {
        Files.copy(src, dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new RuntimeException("Failed to copy file " + src + " to " + dst, e);
    }

    JMeterUtils.loadJMeterProperties(dst.getAbsolutePath());
    JMeterUtils.setLocale(new Locale("ignoreResources"));

    JMeterTreeModel jMeterTreeModel = new JMeterTreeModel();
    JMeterTreeListener jMeterTreeListener = new JMeterTreeListener();
    jMeterTreeListener.setModel(jMeterTreeModel);
    JMeterContextService.getContext().setVariables(new JMeterVariables());
    StandardJMeterEngine engine = new EmulatorJmeterEngine();
    JMeterThreadMonitor monitor = new EmulatorThreadMonitor();
    JMeterContextService.getContext().setEngine(engine);
    HashTree hashtree = new HashTree();
    hashtree.add(new LoopController());
    JMeterThread thread = new JMeterThread(hashtree, monitor, null);
    thread.setThreadName("test thread");
    JMeterContextService.getContext().setThread(thread);
    ThreadGroup threadGroup = new org.apache.jmeter.threads.ThreadGroup();
    threadGroup.setName("test thread group");
    JMeterContextService.getContext().setThreadGroup(threadGroup);
    JMeterUtils.setProperty("sample_variables", "TEST1,TEST2,TEST3"); // for Flexible File Writer Test
    JMeterUtils.setProperty("saveservice_properties", "/ss.props");
    JMeterUtils.setProperty("upgrade_properties", "/ss.props");
    JMeterUtils.setProperty("sampleresult.default.encoding", "UTF-8"); // enable multibyte
}
 
Example 30
Source Project: jmeter-plugins   Source File: ColorsDispatcherFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static ColorsDispatcher getColorsDispatcher() {
    String customDispatcher = JMeterUtils.getProperty("jmeterPlugin.customColorsDispatcher");
    String customOptions = JMeterUtils.getProperty("jmeterPlugin.customColorsDispatcher.options");
    if (customDispatcher != null) {
        if (customDispatcher.equalsIgnoreCase("huerotate")) {
            log.debug("customDispatcher hue rotate");
            return new HueRotatePalette(customOptions);
        } else if (customDispatcher.equalsIgnoreCase("custompalette")) {
            log.debug("customDispatcher custom palette");
            return new CustomPalette(customOptions);
        }
    }
    log.debug("Original boring cycle colors");
    return new CycleColors(); // original "cycle" colors dispatcher
}